﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls.Primitives;
using System.Windows;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Markup;
using System.Security.Principal;
using System.Windows.Resources;
using System.Collections;
using System.Windows.Controls;
using System.Data;
using System.ComponentModel;
using CMD.BAL.CAT;
using CMD.BAL.MISC;
using System.Text.RegularExpressions;
using System.Reflection;
using CMD_DKT.BAL;
using CMD_DKT.Utilities;
using System.Threading;
using System.Runtime.Serialization.Json;
using System.Net;
//using RestSharp;
using System.Windows.Threading;
using CMD_DKT.Synchronization;

namespace CMD_DKT.Sol
{
    public partial class UINuevaSolicitud
    {
        #region Declaracion de variables
        public Border brdr_diasCol;
        public TextBlock txtBlockStatus;
        public TextBox tRazonSocial;
        public TextBox tNumeroSucursal;
        public TextBox tGerencia;
        public TextBox tNoClo;
        public TextBox tNomDPV;
        public TextBox tTitulo;
        public TextBox tIVA;
        public TextBox tRespoFV;
        public TextBox tNoEmpleado;
        public TextBox tCuentaBancaria;
        public TextBox tSucursal;
        public TextBox tNombreSucursal;
        public TextBox tCalle;
        public TextBox tNoExterior;
        public TextBox tNoInterior;
        public TextBox tLada;
        public TextBox tCalleEntrega;
        public TextBox tNoExtEntrega;
        public TextBox tNoInEntrega;
        public TextBox tLadaEntrega;
        public TextBox tEstado;
        public TextBox tEdoEntrega;
        public TextBox tDelMunicipio;
        public TextBox tDelMunEnt;
        public TextBox tRFC;
        public TextBox tEmail;
        public TextBox tTelFiscal;
        public TextBox tTelEnt;
        public TextBox tTelDPV;
        public TextBox tMailDPV;
        public TextBox tSubdir;
        public TextBox tCodigoPostal;
        public TextBox tCoPoEntrega;

        public ComboBox cTipoNegocios;
        public ComboBox cTerritorio; 
        public ComboBox cCenLog;        
        public ComboBox cZona;
        public ComboBox cMedioColoca;
        public ComboBox cFrecuencia;        
        public ComboBox cColoniaDistrito;        
        public ComboBox cColDisEntrega;
        public ComboBox cLeadTime;        
        public ComboBox cClaveBanco;
        public ComboBox cTipoSolicitud;
        public ComboBox cPersona;
        public ComboBox cLocalidad;
        public ComboBox cLocalidadEnt;
        public ComboBox cGrupoClientes4;

        public CheckBox chProveedor;
        public CheckBox chOtrosClientes;
        public CheckBox chOtrasCateg;
        public CheckBox chDiaCL;
        public CheckBox chDiaCM;
        public CheckBox chDiaCMi; 
        public CheckBox chDiaCJ;
        public CheckBox chDiaCV;
        public CheckBox chDiaCS;
        public CheckBox chDiaEL;
        public CheckBox chDiaEM;
        public CheckBox chDiaEMi;
        public CheckBox chDiaEJ;
        public CheckBox chDiaEV;
        public CheckBox chDiaES;
        public CheckBox chMismoDom;

        public ContentControl PanelAccion;
        public ContentControl PanelNavegacion;

        public ScrollViewer PanelCentral;

        public FrameworkElement feNs;
        public List<TextBox> liTxt;
        public List<ComboBox> liCmbx;
        
        public Grid gdDirEntrega;

        public Popup popArchivos;
        public Popup popPrioridad;

        public StackPanel spArchivos;        
        public StackPanel spAlta;
        public StackPanel spPrioridades;

        public Image bdArchivos;
        public Image lblEnviar;
        public Image lblGuardar;
        public Image lblGuardarYSalir;
        public Image bdPrioridad;
        
        //public string nomGene;
        public  string sSolicitudDocs;
        public  string targetPath;
        public string UnidDirFiscal;
        public string UnidDirEntrega;
        public string Regladoc;        
        public string primerArchivo;
        public string cperso;
        public string ctiposol;

        public int mismodomi;
        public int check;
        public int ft;
        public Solicitud sol;

        public Label lbNomBanco;
        public Label lbTipoSolicitud;
        // Lbls de UNIDs de las tablas de relación con la solicitud seleccionada
        public Label lbl_unidSol;
        public Label lbl_unidDatgral;
        public Label lbl_unidDirFiscal;
        public Label lbl_unidDirEntrega;
        public Label lbl_unidRFV;
        public Label lbl_unidDPV;
        public Label lbl_unidInfoad;
        public Label lbl_unidBanc;
        public Label lbl_unidDocinfo;
        public Label lbl_unidInterlocutores;
        public Label lbl_unidWf;
        public Label lbl_unidDocumentos;
        public Label lbl_unidDatos;
        public Label lbl_idPrioridad;
        public Label lbl_idStatus;
        public Label lbl_idTipo;
        public Label lbl_GrupoPrecios;
        public Label lbl_Saving;

        CMDPopUp pop;

        public TextBox tbTelExtEntrega;
        public TextBox tbFaxEnt;
        public TextBox tbFaxExtEntrega;
        public TextBox tbTelExtFiscal;
        public TextBox tbFaxFiscal;
        public TextBox tbFaxExtFiscal;
        #endregion

        public UINuevaSolicitud(ContentControl PA, ContentControl PN, ScrollViewer PC)
        {
            PanelAccion = PA;
            PanelNavegacion = PN;
            PanelCentral = PC;
            PanelAccion.Content = null;
            this.liTxt = new List<TextBox>();
            sol = new Solicitud();
            MainWindow mw = (MainWindow)App.Current.MainWindow;
            lbl_Saving = mw.lbl_Saving;

            #region Cagar Panel de Acción después de accionar ALTA

            string nombre = @".../../BotonesAlta.xaml";

            DependencyObject rootElement;
            using (FileStream fs = new FileStream(nombre, FileMode.Open))
            {
                rootElement = (DependencyObject)XamlReader.Load(fs);
            }

            PanelAccion.Content = rootElement;
            FrameworkElement frameworkElement = (FrameworkElement)rootElement;

            lblEnviar = (Image)frameworkElement.FindName("img_Enviar");
            lblEnviar.MouseUp += new MouseButtonEventHandler(lblEnviar_MouseUp);
            lblEnviar.PreviewMouseUp += new MouseButtonEventHandler(lblEnviar_PreviewMouseDown);

            lblGuardar = (Image)frameworkElement.FindName("img_Guardar");
            lblGuardar.MouseUp += new MouseButtonEventHandler(lblGuardar_MouseUp);
            lblGuardar.PreviewMouseUp += new MouseButtonEventHandler(lblGuardar_PreviewMouseUp);

            //Border lbValidar = (Border)frameworkElement.FindName("lblValidar");
            //lbValidar.MouseUp += new MouseButtonEventHandler(lbValidar_MouseUp);

            Image bdCancelar = (Image)frameworkElement.FindName("img_Cancelar");
            bdCancelar.MouseUp += new MouseButtonEventHandler(bdCancelar_MouseUp);
            
            popArchivos = (Popup)frameworkElement.FindName("popArchivo");
            spArchivos = (StackPanel)frameworkElement.FindName("spArchivos");
            bdArchivos = (Image)frameworkElement.FindName("img_Archivos");
            bdArchivos.MouseUp += new MouseButtonEventHandler(bdArchivos_MouseUp);
            
            popPrioridad = (Popup)frameworkElement.FindName("popPrioridad");
            spPrioridades = (StackPanel)frameworkElement.FindName("spPrioridades");
            bdPrioridad = (Image)frameworkElement.FindName("img_Prioridad");
            bdPrioridad.MouseUp += new MouseButtonEventHandler(bdPrioridad_MouseUp);
            cargarPrioridades();

            //lblGuardarYSalir
            lblGuardarYSalir = (Image)frameworkElement.FindName("img_GuardarYSalir");
            lblGuardarYSalir.MouseUp += new MouseButtonEventHandler(lblGuardar_MouseUp);
            lblGuardarYSalir.PreviewMouseUp += new MouseButtonEventHandler(lblGuardar_PreviewMouseUp);

            Image lblInfoDoc = (Image)frameworkElement.FindName("img_InfoDoc");
            lblInfoDoc.MouseUp += new MouseButtonEventHandler(lblInfoDoc_MouseUp);

            txtBlockStatus = (TextBlock)frameworkElement.FindName("txtBlock_Status");
            #endregion


            #region Buscar elementos de Nueva Solicitud
            
            string nombrens = @"../../NuevaSolicitud.xaml";
            DependencyObject rootElementns;
            using (FileStream fsns = new FileStream(nombrens, FileMode.Open))
            {
                rootElementns = (DependencyObject)XamlReader.Load(fsns);
            }

            PanelCentral.Content = rootElementns;
            FrameworkElement frameworkElementns = (FrameworkElement)rootElementns;
            this.feNs = frameworkElementns;

            spAlta = (StackPanel)frameworkElementns.FindName("spAlta");
            lbl_unidSol = (Label)frameworkElementns.FindName("lbl_unidSol");
            lbl_unidDatgral = (Label)frameworkElementns.FindName("lbl_unidDatgral");
            lbl_unidDirFiscal = (Label)frameworkElementns.FindName("lbl_unidDirFiscal");
            lbl_unidDirEntrega = (Label)frameworkElementns.FindName("lbl_unidDirEntrega");
            lbl_unidRFV = (Label)frameworkElementns.FindName("lbl_unidRFV");
            lbl_unidDPV = (Label)frameworkElementns.FindName("lbl_unidDPV");
            lbl_unidInfoad = (Label)frameworkElementns.FindName("lbl_unidInfoad");
            lbl_unidBanc = (Label)frameworkElementns.FindName("lbl_unidBanc");
            lbl_unidDocinfo = (Label)frameworkElementns.FindName("lbl_unidDocinfo");
            lbl_unidInterlocutores = (Label)frameworkElementns.FindName("lbl_unidInterlocutores");
            lbl_unidWf = (Label)frameworkElementns.FindName("lbl_unidWf");
            lbl_unidDocumentos = (Label)frameworkElementns.FindName("lbl_unidDocumentos");
            lbl_unidDatos = (Label)frameworkElementns.FindName("lbl_unidDatos");
            lbl_idPrioridad = (Label)frameworkElementns.FindName("lbl_idPrioridad");
            lbl_idStatus = (Label)frameworkElementns.FindName("lbl_idStatus");
            lbl_idTipo = (Label)frameworkElementns.FindName("lbl_idTipo");
            lbl_idTipo.Content = "1";
            lbl_idPrioridad.Content = "3";

            #region Controles de la sección de Nueva Solicitud
            lbTipoSolicitud = (Label)frameworkElementns.FindName("lblTipoSolicitud");
            lbTipoSolicitud.Content = "Alta";
            gdDirEntrega = (Grid)frameworkElementns.FindName("gdDirEntrega");
            cTipoSolicitud = (ComboBox)frameworkElementns.FindName("cbTipoSolicitud");
            cTipoSolicitud.SelectionChanged += new SelectionChangedEventHandler(cTipoSolicitud_SelectionChanged);
            chProveedor = (CheckBox)frameworkElementns.FindName("chbProveedor");
            chMismoDom = (CheckBox)frameworkElementns.FindName("chbMismoDom");
            chOtrosClientes = (CheckBox)frameworkElementns.FindName("chbOtrosClientes");
            cPersona = (ComboBox)frameworkElementns.FindName("cbPersona");
            cPersona.SelectionChanged += new SelectionChangedEventHandler(cPersona_SelectionChanged);
            chOtrasCateg = (CheckBox)frameworkElementns.FindName("chbOtrasCateg");

            //chMismoDom.Click += new RoutedEventHandler(chMismoDom_Click);
            chOtrosClientes.Click += new RoutedEventHandler(chOtrosClientes_Click);
            chMismoDom.Checked += new RoutedEventHandler(chMismoDom_Click);
            chMismoDom.Unchecked += new RoutedEventHandler(chMismoDom_Click);
            #endregion  
            #region Controles de la sección Datos Generales
            cTipoNegocios = (ComboBox)frameworkElementns.FindName("cbTipoNegocios");
            tRazonSocial = (TextBox)frameworkElementns.FindName("tbRazonSocial");
            tRazonSocial.LostFocus += new RoutedEventHandler(tRazonSocial_LostFocus);
            tRazonSocial.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DATOSGRAL", "RAZON_SOCIAL")).Rows[0]["LARGO"].ToString()));
            cGrupoClientes4 = (ComboBox)frameworkElementns.FindName("cbGrupoClientes4");
            tRFC = (TextBox)frameworkElementns.FindName("tbRFC");
            tRFC.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DATOSGRAL", "RFC")).Rows[0]["LARGO"].ToString()));
            tRFC.LostFocus += new RoutedEventHandler(tRFC_LostFocus);
            tEmail = (TextBox)frameworkElementns.FindName("tbEmail");
            tEmail.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DATOSGRAL", "CORREO")).Rows[0]["LARGO"].ToString()));
            tNumeroSucursal = (TextBox)frameworkElementns.FindName("tbNumeroSucursal");
            tNumeroSucursal.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DATOSGRAL", "NUMERO_SUCURSAL")).Rows[0]["LARGO"].ToString()));
            tNombreSucursal = (TextBox)frameworkElementns.FindName("tbNombreSucursal");
            tNombreSucursal.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DATOSGRAL", "NOMBRE_SUCURSAL")).Rows[0]["LARGO"].ToString()));
            tEmail.LostFocus += new RoutedEventHandler(Email_LostFocus);
            tNombreSucursal.LostFocus += new RoutedEventHandler(tNombreSucursal_LostFocus);
            tNumeroSucursal.LostFocus += new RoutedEventHandler(tNumeroSucursal_LostFocus);

            #endregion

            #region Controles de la sección Dirección Fiscal
            tCalle = (TextBox)frameworkElementns.FindName("tbCalle");
            tCalle.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DIRFISCAL", "CALLE")).Rows[0]["LARGO"].ToString()));
            tCalle.LostFocus += new RoutedEventHandler(tCalle_LostFocus);
            tNoExterior = (TextBox)frameworkElementns.FindName("tbNoExterior");
            tNoExterior.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DIRFISCAL", "NUMERO_EXTERIOR")).Rows[0]["LARGO"].ToString()));
            tNoExterior.LostFocus += new RoutedEventHandler(tNoExterior_LostFocus);
            tNoInterior = (TextBox)frameworkElementns.FindName("tbNoInterior");
            tNoInterior.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DIRFISCAL", "NUMERO_INTERIOR")).Rows[0]["LARGO"].ToString()));
            tNoInterior.LostFocus += new RoutedEventHandler(tNoInterior_LostFocus);
            tCodigoPostal = (TextBox)frameworkElementns.FindName("tbCodigoPostal");   
            tDelMunicipio = (TextBox)frameworkElementns.FindName("tbDelMunicipio");
            cColoniaDistrito = (ComboBox)frameworkElementns.FindName("cbColoniaDistrito");
            cLocalidad = (ComboBox)frameworkElementns.FindName("cbLocalidad");
            tEstado = (TextBox)frameworkElementns.FindName("tbEstado");
            
            tLada = (TextBox)frameworkElementns.FindName("tbLada");
            tLada.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DIRFISCAL", "LADA")).Rows[0]["LARGO"].ToString()));
            tLada.LostFocus += new RoutedEventHandler(tLada_LostFocus);
            tTelFiscal = (TextBox)frameworkElementns.FindName("tbTelFiscal");
            tTelFiscal.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DIRFISCAL", "TELEFONO")).Rows[0]["LARGO"].ToString()));
            tTelFiscal.LostFocus += new RoutedEventHandler(tTelFiscal_LostFocus);
            tEstado.IsEnabled = false;
            tDelMunicipio.IsEnabled = false;

            tbFaxEnt = (TextBox)frameworkElementns.FindName("tbFaxEnt");
            tbFaxEnt.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DIRENTREGA", "FAX_NUMBER")).Rows[0]["LARGO"].ToString()));
            tbFaxExtEntrega = (TextBox)frameworkElementns.FindName("tbFaxExtEntrega");
            tbFaxExtEntrega.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DIRENTREGA", "FAX_EXTENS")).Rows[0]["LARGO"].ToString()));
            tbTelExtEntrega = (TextBox)frameworkElementns.FindName("tbTelExtEntrega");
            tbTelExtEntrega.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DIRENTREGA", "TEL_EXTENS")).Rows[0]["LARGO"].ToString()));

            tbTelExtFiscal = (TextBox)frameworkElementns.FindName("tbTelExtFiscal");
            tbTelExtFiscal.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DIRFISCAL", "TEL_EXTENS")).Rows[0]["LARGO"].ToString()));
            tbFaxExtFiscal = (TextBox)frameworkElementns.FindName("tbFaxExtFiscal");
            tbFaxExtFiscal.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DIRFISCAL", "FAX_EXTENS")).Rows[0]["LARGO"].ToString()));
            tbFaxFiscal = (TextBox)frameworkElementns.FindName("tbFaxFiscal");
            tbFaxFiscal.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DIRFISCAL", "FAX_NUMBER")).Rows[0]["LARGO"].ToString()));            

            tCalle.TextChanged += new TextChangedEventHandler(tCalle_TextChanged);
            tNoExterior.TextChanged += new TextChangedEventHandler(tNoExterior_TextChanged);
            tNoInterior.TextChanged += new TextChangedEventHandler(tNoInterior_TextChanged);
            tCodigoPostal.LostFocus += new RoutedEventHandler(tCodigoPostal_LostFocus);
            tCodigoPostal.TextChanged += new TextChangedEventHandler(tCodigoPostal_TextChanged);
            tLada.TextChanged += new TextChangedEventHandler(tLada_TextChanged);
            cColoniaDistrito.SelectionChanged += new SelectionChangedEventHandler(cColoniaDistrito_SelectionChanged);
            cLocalidad.SelectionChanged += new SelectionChangedEventHandler(cLocalidad_SelectionChanged);
            tTelFiscal.TextChanged += new TextChangedEventHandler(tTelFiscal_TextChanged);
            tTelFiscal.LostFocus += new RoutedEventHandler(tTel_LostFocus);

            
            tbTelExtFiscal.TextChanged +=new TextChangedEventHandler(tbTelExtFiscal_TextChanged);
            tbFaxFiscal.TextChanged +=new TextChangedEventHandler(tbFaxFiscal_TextChanged);
            tbFaxExtFiscal.TextChanged +=new TextChangedEventHandler(tbFaxExtFiscal_TextChanged);

            tbTelExtFiscal.LostFocus += new RoutedEventHandler(tbTelExt_LostFocus);
            tbFaxFiscal.LostFocus += new RoutedEventHandler(tbFax_LostFocus);
            tbFaxExtFiscal.LostFocus += new RoutedEventHandler(tbFaxExt_LostFocus);
            #endregion

            #region Controles de la sección Dirección de Entrega
            tCalleEntrega = (TextBox)frameworkElementns.FindName("tbCalleEntrega");
            tCalleEntrega.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DIRENTREGA", "CALLE")).Rows[0]["LARGO"].ToString()));
            tCalleEntrega.LostFocus += new RoutedEventHandler(tCalleEntrega_LostFocus);
            tNoExtEntrega = (TextBox)frameworkElementns.FindName("tbNoExtEntrega");
            tNoExtEntrega.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DIRENTREGA", "NUMERO_EXTERIOR")).Rows[0]["LARGO"].ToString()));
            tNoExtEntrega.LostFocus += new RoutedEventHandler(tNoExtEntrega_LostFocus);
            tNoInEntrega = (TextBox)frameworkElementns.FindName("tbNoIntEntrega");
            tNoInEntrega.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DIRENTREGA", "NUMERO_INTERIOR")).Rows[0]["LARGO"].ToString()));
            tNoInEntrega.LostFocus += new RoutedEventHandler(tNoInEntrega_LostFocus);
            tCoPoEntrega = (TextBox)frameworkElementns.FindName("tbCopoEntrega");
            cLocalidadEnt = (ComboBox)frameworkElementns.FindName("cbLocalidadEnt");
            tCoPoEntrega.LostFocus += new RoutedEventHandler(tCoPoEntrega_LostFocus);
            tDelMunEnt = (TextBox)frameworkElementns.FindName("tbDelMunEnt");
            cColDisEntrega = (ComboBox)frameworkElementns.FindName("cbColDisEntrega");
            tEdoEntrega = (TextBox)frameworkElementns.FindName("tbEdoEntrega");
           // tEdoEntrega.TextChanged += new TextChangedEventHandler(tEdoEntrega_TextChanged);
            tLadaEntrega = (TextBox)frameworkElementns.FindName("tbLadaEntrega");
            tLadaEntrega.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DIRENTREGA", "LADA")).Rows[0]["LARGO"].ToString()));
            tLadaEntrega.LostFocus += new RoutedEventHandler(tLadaEntrega_LostFocus);
            tTelEnt = (TextBox)frameworkElementns.FindName("tbTelEnt");
            tTelEnt.LostFocus+=new RoutedEventHandler(tTel_LostFocus);
            
            tTelEnt.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DIRENTREGA", "TELEFONO")).Rows[0]["LARGO"].ToString()));
            tEdoEntrega.IsEnabled = false;
            tDelMunEnt.IsEnabled = false;
            
            tbTelExtEntrega.LostFocus += new RoutedEventHandler(tbTelExt_LostFocus);
            tbFaxEnt.LostFocus += new RoutedEventHandler(tbFax_LostFocus);
            tbFaxExtEntrega.LostFocus += new RoutedEventHandler(tbFaxExt_LostFocus);
            #endregion

            #region Controles de la sección Responsable Fuerza de Ventas
            cTerritorio = (ComboBox)frameworkElementns.FindName("cbTerritorio");
            cLeadTime = (ComboBox)frameworkElementns.FindName("cbLeadTime");
            tSubdir = (TextBox)frameworkElementns.FindName("tbSubdir");
            tGerencia = (TextBox)frameworkElementns.FindName("tbGerencia");
            cCenLog = (ComboBox)frameworkElementns.FindName("cbCenLog");
            tNoClo = (TextBox)frameworkElementns.FindName("tbNoClo");
            cTerritorio.SelectionChanged += new SelectionChangedEventHandler(cTerritorio_SelectionChanged);
            cCenLog.SelectionChanged += new SelectionChangedEventHandler(cCenLog_SelectionChanged);
            cLeadTime.SelectionChanged += new SelectionChangedEventHandler(cLeadTime_SelectionChanged);
            #endregion

            #region Controles Datos Perfil de Ventas
            tNomDPV = (TextBox)frameworkElementns.FindName("tbNomDPV");
            tNomDPV.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DPV", "NOMBRE")).Rows[0]["LARGO"].ToString()));
            tNomDPV.LostFocus += new RoutedEventHandler(tNomDPV_LostFocus);
            tTelDPV = (TextBox)frameworkElementns.FindName("tbTelDPV");
            tTelDPV.LostFocus += new RoutedEventHandler(tTel_LostFocus);
            tTelDPV.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DPV", "TELEFONO")).Rows[0]["LARGO"].ToString()));
            tTitulo = (TextBox)frameworkElementns.FindName("tbTitulo");
            tTitulo.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DPV", "TITULO")).Rows[0]["LARGO"].ToString()));
            tTitulo.LostFocus += new RoutedEventHandler(tTitulo_LostFocus);
            tMailDPV = (TextBox)frameworkElementns.FindName("tbMailDPV");
            tMailDPV.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DPV", "CORREO")).Rows[0]["LARGO"].ToString()));
            cZona = (ComboBox)frameworkElementns.FindName("cbZona");
            cZona.SelectionChanged+=new SelectionChangedEventHandler(cZona_SelectionChanged);
            tIVA = (TextBox)frameworkElementns.FindName("tbIVA");
            cMedioColoca = (ComboBox)frameworkElementns.FindName("cbMedioColoca");
            lbl_GrupoPrecios = (Label)frameworkElementns.FindName("lblGrupoPrecios");
            cFrecuencia = (ComboBox)frameworkElementns.FindName("cbFrecuencia");
            brdr_diasCol = (Border)frameworkElementns.FindName("brdr_diasCol");
            chDiaCL = (CheckBox)frameworkElementns.FindName("chbDiaC1");
            chDiaCM = (CheckBox)frameworkElementns.FindName("chbDiaC2");
            chDiaCMi = (CheckBox)frameworkElementns.FindName("chbDiaC3");
            chDiaCJ = (CheckBox)frameworkElementns.FindName("chbDiaC4");
            chDiaCV = (CheckBox)frameworkElementns.FindName("chbDiaC5");
            chDiaCS = (CheckBox)frameworkElementns.FindName("chbDiaC6");

            chDiaEL = (CheckBox)frameworkElementns.FindName("chbDiaE1");
            chDiaEM = (CheckBox)frameworkElementns.FindName("chbDiaE2");
            chDiaEMi = (CheckBox)frameworkElementns.FindName("chbDiaE3");
            chDiaEJ = (CheckBox)frameworkElementns.FindName("chbDiaE4");
            chDiaEV = (CheckBox)frameworkElementns.FindName("chbDiaE5");
            chDiaES = (CheckBox)frameworkElementns.FindName("chbDiaE6");

            chDiaCL.Checked += new RoutedEventHandler(chDiaC_Click);
            chDiaCM.Checked += new RoutedEventHandler(chDiaC_Click);
            chDiaCMi.Checked += new RoutedEventHandler(chDiaC_Click);
            chDiaCJ.Checked += new RoutedEventHandler(chDiaC_Click);
            chDiaCV.Checked += new RoutedEventHandler(chDiaC_Click);
            chDiaCS.Checked += new RoutedEventHandler(chDiaC_Click);

            chDiaCL.Unchecked += new RoutedEventHandler(chDiaC_Click);
            chDiaCM.Unchecked += new RoutedEventHandler(chDiaC_Click);
            chDiaCMi.Unchecked += new RoutedEventHandler(chDiaC_Click);
            chDiaCJ.Unchecked += new RoutedEventHandler(chDiaC_Click);
            chDiaCV.Unchecked += new RoutedEventHandler(chDiaC_Click);
            chDiaCS.Unchecked += new RoutedEventHandler(chDiaC_Click);

            tMailDPV.LostFocus += new RoutedEventHandler(Email_LostFocus);

            #endregion

            #region Controles de la sección Información Adicional
            tRespoFV = (TextBox)frameworkElementns.FindName("tbRFV");
            tNoEmpleado = (TextBox)frameworkElementns.FindName("tbNoEmpleado");

            #endregion

            #region Controles de la sección Datos Bancarios
            cClaveBanco = (ComboBox)frameworkElementns.FindName("cbClaveBanco");
            cClaveBanco.SelectionChanged += new SelectionChangedEventHandler(cClaveBanco_SelectionChanged);

            lbNomBanco = (Label)frameworkElementns.FindName("lblNomBanco");
            tCuentaBancaria = (TextBox)frameworkElementns.FindName("tbCuentaBancaria");
            tCuentaBancaria.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DATOSBANC", "CTA_BANCARIA")).Rows[0]["LARGO"].ToString()));
            tSucursal = (TextBox)frameworkElementns.FindName("tbSucursal");
            tSucursal.MaxLength = (System.Convert.ToInt32(((DataTable)TableLength.GetData("CMD_SOLICITUD_DATOSBANC", "SUCURSAL")).Rows[0]["LARGO"].ToString()));
            tCuentaBancaria.LostFocus += new RoutedEventHandler(tCuentaBancaria_LostFocus);
            tSucursal.LostFocus += new RoutedEventHandler(tSucursal_LostFocus);
            #endregion
            #endregion


            #region Carga de Combobox con Stored Procedure
            DataTable dt = TipoSolicitante.GetData();

            chMismoDom.Click -= new RoutedEventHandler(chMismoDom_Click);
            cPersona.SelectionChanged -= new SelectionChangedEventHandler(cPersona_SelectionChanged);
            cTipoSolicitud.SelectionChanged -= new SelectionChangedEventHandler(cTipoSolicitud_SelectionChanged);

            cargarcombos(cTipoSolicitud, dt,"DSC_TIPO_SOLICITANTE", "UNID_TIPO_SOLICITANTE" );

            dt = TipoPersonaFisica.GetData();
            cargarcombos(cPersona, dt, "DSC_TIPO_PERSONA_FISCAL","ID_TIPO_PERSONA_FISCAL");

            dt = TipoNegocio.GetData();
            cargarcombos(cTipoNegocios, dt,"DSC_TIPO_NEGOCIO", "ID_TIPO_NEGOCIO");
            
            dt = LeadTime.GetData();
            cargarcombos(cLeadTime, dt, "TRANSPORTE","ID_LEADTIME");

            dt = MedioColocacion.GetData();
            cargarcombos(cMedioColoca, dt, "DSC_MED_COLOCACION", "ID_MED_COLOCACION");

            dt = Frecuencia.GetData();
            cargarcombos(cFrecuencia, dt, "DSC_FRECUENCIA", "ID_FRECUENCIA");

            dt = Banco.GetData();
            cargarcombos(cClaveBanco, dt, "ID_BANCO", "ID_BANCO");

            dt = Clo.GetData();
            cargarcombos(cCenLog, dt, "DSCyVENTA", "ID_CLO");
            if (dt.Rows.Count != 0) cCenLog.SelectedIndex = 0; else cCenLog.SelectedIndex = -1;

            dt = Clientes4.GetData();
            cargarcombos(cGrupoClientes4, dt, "DSC_GRUPOCLIENTES4", "ID_GRUPOCLIENTES4");

            cClaveBanco_SelectionChanged(null, null);

            //SECCION RESPONSABLE FUERZA DE VENTAS
            ObtieneRespVentas fvtas = new ObtieneRespVentas();
            dt = Estructura.GetData(5, "null");
            //if ((bool)chOtrosClientes.IsChecked)
            //      dt = Estructura.GetData(5, "null");
            //else
            //    dt = Estructura.GetData(5, fvtas.IdTerritorio);
            cargarcombos(cTerritorio, dt, "DSC_ESTRUCTURA", "ID_CODIGO");

            cTerritorio_SelectionChanged(null, null);


           
            cTerritorio.IsEnabled = false;
            dt = Estructura.GetData(5, fvtas.IdTerritorio);
            cTerritorio.SelectedValue = dt.Rows[0][0].ToString();

            //SECCION INFORMACION ADICIONAL

            tRespoFV.Text = fvtas.Nombre;
            tNoEmpleado.Text = fvtas.HRCode;
            cTerritorio_SelectionChanged(null, null);
            #endregion

          

            #region Carga del Panel de Navegación después de accionar ALTA
            string nombre2 = @".../../Secciones.xaml";

            DependencyObject rootElement2;
            using (FileStream fs2 = new FileStream(nombre2, FileMode.Open))
            {
                rootElement2 = (DependencyObject)XamlReader.Load(fs2);
            }

            PanelNavegacion.Content= rootElement2;
            FrameworkElement frameworkElement2 = (FrameworkElement)rootElement2;
            ArrayList al = SolAlta.UISolAlta.GetSecRanges();


            #endregion


            #region Pegar eventos a los botones de navegacion

            //Pegar eventos a los botones de navegacion
            Grid grdNav01 = (Grid)frameworkElement2.FindName("grdNavSolicitudAlta");
            foreach (Object tmp in grdNav01.Children)
            {
                if (tmp is Border)
                {
                    Border tmpBrd = (Border)tmp;
                    //Point relativePoint = new Point();
                    tmpBrd.MouseUp += delegate(object sender3, MouseButtonEventArgs e3)
                    {
                        double tgt = 0;
                        Grid _brdNavgrdNav01 = (Grid)frameworkElement2.FindName("grdNavSolicitudAlta");
                        foreach (Object __tmp in _brdNavgrdNav01.Children)
                        {
                            if (__tmp is Border)
                            {
                                Border __tmpBrd = (Border)__tmp;
                                __tmpBrd.Background = Brushes.Transparent;
                            }
                        }

                        foreach (SolAlta.NavSecRange ns in al)
                        {
                            if (ns.controlName == ((Border)sender3).Name)
                            {
                                tgt = ns.SEC_INI;
                            }
                        }

                        ((Border)sender3).Background = Brushes.White;
                        PanelCentral.ScrollToVerticalOffset(tgt);
                        //PanelCentral.ScrollToVerticalOffset(relativePoint.Y);
                        //scrollViewer1.ScrollToVerticalOffset(tgt);
                    };
                }
            }

            #endregion

            #region efecto scroll
            //Function para cambiar automaticamente de etiqueta cuando se hace scroll
            this.PanelCentral.ScrollChanged += delegate(object sender2, ScrollChangedEventArgs e2)
            {
                foreach (SolAlta.NavSecRange ns in al)
                {
                    if (e2.VerticalOffset >= ns.SEC_INI && e2.VerticalOffset <= ns.SEC_END)
                    {
                        Grid grdNav = (Grid)frameworkElement2.FindName("grdNavSolicitudAlta");
                        foreach (Object tmp in grdNav.Children)
                        {
                            if (tmp is Border)
                            {
                                Border tmpBrd = (Border)tmp;
                                var converter = new System.Windows.Media.BrushConverter();
                                tmpBrd.Background = Brushes.Transparent;

                                Border sel = (Border)frameworkElement2.FindName(ns.controlName);
                                sel.Background = Brushes.White;
                            }
                        }
                    }
                }
            };

            #endregion

            cTipoNegocios.SelectionChanged += new SelectionChangedEventHandler(cTipoNegocios_SelectionChanged);

            targetPath = System.Configuration.ConfigurationManager.AppSettings["ClientDocsFolder"];
            primerArchivo = "-1";
            sSolicitudDocs = "-1";
            cperso = cPersona.SelectedValue.ToString();
            ctiposol = cTipoSolicitud.SelectedValue.ToString();
            targetPath = AppConfs.ClientDocsFolder;
            if (chMismoDom.IsChecked == true)
                check = 1;
            else 
                check = 0;

           tRFC.MaxLength = (((DataRowView)(((Selector)(cPersona)).SelectedItem)).Row["DSC_TIPO_PERSONA_FISCAL"].ToString() == "moral") ? 12 : 13;
            //ft = 0;
           PanelCentral.ScrollToVerticalOffset(0);

           
        }

       

        virtual public bool ValidarEnviado()
        {
            
            bool bandera = true;
            string sArchivos;
            cargaListTextBox();
            foreach (TextBox tx in liTxt)
                if (tx.Text.Length == 0)
                {
                    pintarError(tx);
                    bandera = false;
                }
                else
                {
                    pintarCorrecto(tx);
                }

            if (!ValidarRFC(tRFC))
                bandera = false;
            if (!ValidarEmail(tEmail))
                bandera = false;
            if (!ValidarEmail(tMailDPV))
                bandera = false;
            if (!ValidarTelefono(tTelDPV))
                bandera = false;
            if (!ValidarTelefono(tTelEnt))
                bandera = false;
            if (!ValidarTelefono(tTelFiscal))
                bandera = false;
            if (!ValidarDiasColoc())
                bandera = false;
            if (chMismoDom.IsChecked == true)
            {
                if (tCodigoPostal.Text != "" && tCoPoEntrega.Text != "")
                    if (!ValidarCodigoPostal(tCodigoPostal))
                        bandera = false;
            }
            else
            {
                if (!ValidarCodigoPostal(tCodigoPostal))
                    bandera = false;
                if (!ValidarCodigoPostal(tCoPoEntrega))
                    bandera = false;
            }
            if (!bandera)
            {
                MessageBox.Show("La solicitud no puede ser Enviada. Revise y valide los campos marcados", "Atención", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return bandera;
            }

            if (!validaArchivos(out sArchivos))
            {
                MessageBox.Show(sArchivos, "Atención", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                bandera = false;
            }

            return bandera;
        }

        #region LostFocus Event Handlers

        public virtual void tRazonSocial_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text == "")
                return;
            else {
                pintarCorrecto(tRazonSocial);
            }
        }

        public virtual void tNombreSucursal_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }

        public static void setTbToBlank(object sender)
        {
            TextBox tx = (TextBox)sender;
            tx.BorderBrush = new SolidColorBrush(SystemColors.ActiveBorderColor);
            tx.Background = new SolidColorBrush(Colors.White);
            tx.Foreground = new SolidColorBrush(Colors.Black);
        }

        public virtual void tNumeroSucursal_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }


        public virtual void tTelFiscal_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }

        public virtual void tNoInterior_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }

        public virtual void tLada_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }

        public virtual void tNoExterior_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }

        public virtual void tCalle_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }

        public virtual void tLadaEntrega_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }

        public virtual void tNoInEntrega_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }

        public virtual void tNoExtEntrega_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }

        public virtual void tCalleEntrega_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }

        public virtual void tTitulo_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }

        public virtual void tNomDPV_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }

        public virtual void tSucursal_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }

        public virtual void tCuentaBancaria_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }

        public virtual void tRFC_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text == "")
                return;
            ValidarRFC((TextBox)sender);
        }


        public virtual void tbFaxExt_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }

        public virtual void tbFax_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }

        public virtual void tbTelExt_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                setTbToBlank(sender);
        }


        public void tTel_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text == "")
                return;
            ValidarTelefono((TextBox)sender);
        }

        public void Email_LostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text == "")
                return;
            ValidarEmail((TextBox)sender);
        }


        #endregion




        public void lblInfoDoc_MouseUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (lbl_unidDocinfo.Content.ToString().Trim() != "-1")
                {
                    InfoDoc.DocInfo wndInfo = new InfoDoc.DocInfo(lbl_unidDocinfo.Content.ToString());
                    MainWindow mw = (MainWindow)App.Current.MainWindow;
                    wndInfo.Owner = mw.Owner;
                    wndInfo.ShowDialog();
                }
                else
                    MessageBox.Show("El documento no tiene información", "Información", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        public void lblGuardarYSalir_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (sol.Id_status > 1)
            {
                MessageBox.Show("La solicitud se encuentra en un estatus distinto de Borrador, no es posible editarla.\n",
                    "Mensaje del Sistema", MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK, MessageBoxOptions.DefaultDesktopOnly);
                return;
            }

            Sol.UISolicitudes Despliega = new Sol.UISolicitudes(PanelAccion, PanelNavegacion, PanelCentral);
        }

        public void setLengthRFC()
        {
            tRFC.MaxLength = Convert.ToInt32((((DataRowView)(((Selector)(cPersona)).SelectedItem)).Row["TIPO_PERSONA_LENGTH"].ToString()));
            if (tRFC.MaxLength < tRFC.Text.Length)
                tRFC.Text = tRFC.Text.Remove(tRFC.MaxLength, tRFC.Text.Length - tRFC.MaxLength);
            if(tRFC.Text!="")
                ValidarRFC(tRFC);
        }

        public void cargarPrioridades()
        {
            StackPanel stkPanDoc;
            
            Image imgEstatus;
            TextBlock txtBlockPrioridad;
            DataTable dt;
            try
            {
                dt=Prioridad.GetData();
                foreach (DataRow row in dt.Rows)
                {
                    BitmapImage bi2 = new BitmapImage();
                    stkPanDoc = new StackPanel();
                    
                    imgEstatus = new Image();
                    txtBlockPrioridad = new TextBlock();
                    stkPanDoc.Name = row["DSC_PRIORIDAD"].ToString();
                    txtBlockPrioridad.Text = row["DSC_PRIORIDAD"].ToString();
                    txtBlockPrioridad.Margin = new Thickness(5, 0, 5, 0);
                    stkPanDoc.Orientation = Orientation.Horizontal;
                    imgEstatus.Stretch = Stretch.Fill;
                    bi2.BeginInit();
                    bi2.UriSource = new Uri(row["PATH_IMAGEN"].ToString(), UriKind.Relative);
                    bi2.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                    bi2.DecodePixelHeight = 15;
                    bi2.EndInit();
                    imgEstatus.Source = bi2;
                    imgEstatus.Margin = new Thickness(5, 0, 5, 4);
                    stkPanDoc.Children.Add(imgEstatus);
                    stkPanDoc.Children.Add(txtBlockPrioridad);
                    stkPanDoc.Cursor = Cursors.Hand;
                    stkPanDoc.MouseEnter += new MouseEventHandler(stkPanDoc_MouseEnter);
                    stkPanDoc.MouseLeave += new MouseEventHandler(stkPanDoc_MouseLeave);
                    spPrioridades.Children.Add(stkPanDoc);
                    stkPanDoc.MouseUp += delegate(object sender3, MouseButtonEventArgs e3) { PrioridadesClick(sender3, e3); };
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        void stkPanDoc_MouseLeave(object sender, MouseEventArgs e)
        {
            ((StackPanel)sender).Background =new SolidColorBrush(Colors.GhostWhite);
        }

        void stkPanDoc_MouseEnter(object sender, MouseEventArgs e)
        {
            BrushConverter bc = new BrushConverter();
            Brush b;
            b = (Brush)bc.ConvertFrom("#f0f0f0");
            ((StackPanel)sender).Background = b;
        }

        private void PrioridadesClick(object sender3, MouseButtonEventArgs e3)
        {
            try
            {
                String sPrioridad;
                StackPanel stck_Priori=(StackPanel)sender3;
                sPrioridad = stck_Priori.Name;
                DataTable dt = Prioridad.GetData();
                var results = from DataRow myRow in dt.Rows
                              where myRow.Field<string>("DSC_PRIORIDAD") == sPrioridad
                              select myRow;

                DataTable dattabb = results.CopyToDataTable();
                lbl_idPrioridad.Content = dattabb.Rows[0]["ID_PRIORIDAD"].ToString();
                setImagenPrioridad();
            }
            catch(Exception ex)
            {
                throw ex;
            }

        }

        public void setImagenPrioridad()
        {
            try
            {
                DataTable dt = Prioridad.GetData();
                var results = from DataRow myRow in dt.Rows
                              where myRow.Field<int>("ID_PRIORIDAD") == Convert.ToInt32(lbl_idPrioridad.Content)
                              select myRow;
                dt = results.CopyToDataTable();
                popPrioridad.IsOpen = false;
                BitmapImage bi2 = new BitmapImage();
                bi2.BeginInit();
                bi2.UriSource = new Uri(dt.Rows[0]["PATH_IMAGEN"].ToString(), UriKind.Relative);
                bi2.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                bi2.EndInit();
                bdPrioridad.Stretch = Stretch.Fill;
                bdPrioridad.Source = bi2;
                //BrushConverter bc = new BrushConverter();
                //Brush b;
                //b = (Brush)bc.ConvertFrom("#"+dt.Rows[0]["RGB_COLOR"].ToString());
            }
            catch(Exception ex  )
            {
                throw ex;
            }
        }

        public void bdPrioridad_MouseUp(object sender, MouseButtonEventArgs e)
        {
            popPrioridad.PlacementTarget = (Image)sender;
            popPrioridad.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
            if (spPrioridades.IsEnabled)
                popPrioridad.IsOpen = true;
        }

        public void cLeadTime_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                chDiaEL.IsChecked = false;
                chDiaEM.IsChecked = false;
                chDiaEMi.IsChecked = false;
                chDiaEJ.IsChecked = false;
                chDiaEV.IsChecked = false;
                chDiaES.IsChecked = false;
                ComboBox comboLead = (ComboBox)sender;
                if(chDiaCL.IsChecked==true)
                {
                    chDiaCL.IsChecked=false;
                    chDiaCL.IsChecked=true;
                }
                if(chDiaCM.IsChecked==true)
                {
                    chDiaCM.IsChecked=false;
                    chDiaCM.IsChecked=true;
                }
                if(chDiaCMi.IsChecked==true)
                {
                    chDiaCMi.IsChecked=false;
                    chDiaCMi.IsChecked=true;
                }
                 if(chDiaCJ.IsChecked==true)
                {
                    chDiaCJ.IsChecked=false;
                    chDiaCJ.IsChecked=true;
                }
                if(chDiaCV.IsChecked==true)
                {
                    chDiaCV.IsChecked=false;
                    chDiaCV.IsChecked=true;
                }
                 if(chDiaCS.IsChecked==true)
                {
                    chDiaCS.IsChecked=false;
                    chDiaCS.IsChecked=true;
                }  
                //comboLead.SelectedValue;
            }
            catch
            {
            }
        }

        public void chDiaC_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckBox DiaColoc = (CheckBox)sender;
                Int32 iDiaEntreg;
                Boolean Checked = (DiaColoc.IsChecked==true) ? true : false;

                iDiaEntreg = Convert.ToInt32(DiaColoc.Name.Substring(DiaColoc.Name.Length - 1, 1));
                iDiaEntreg+=Convert.ToInt32(cLeadTime.SelectedValue);
                iDiaEntreg += 1;
                if (iDiaEntreg > 6)
                    iDiaEntreg -= 6;

                switch ("chbDiaE" + iDiaEntreg.ToString())
                {
                    case "chbDiaE1":
                        chDiaEL.IsChecked = Checked;
                        break;
                    case "chbDiaE2":
                        chDiaEM.IsChecked = Checked;
                        break;
                    case "chbDiaE3":
                        chDiaEMi.IsChecked = Checked;
                        break;
                    case "chbDiaE4":
                        chDiaEJ.IsChecked = Checked;
                        break;
                    case "chbDiaE5":
                        chDiaEV.IsChecked = Checked;
                        break;
                    case "chbDiaE6":
                        chDiaES.IsChecked = Checked;
                        break;
                }
                brdr_diasCol.Background = new SolidColorBrush(Colors.White);
                chDiaCL.Foreground = new SolidColorBrush(Colors.Black);
                chDiaCM.Foreground = new SolidColorBrush(Colors.Black);
                chDiaCMi.Foreground = new SolidColorBrush(Colors.Black);
                chDiaCJ.Foreground = new SolidColorBrush(Colors.Black);
                chDiaCV.Foreground = new SolidColorBrush(Colors.Black);
                chDiaCS.Foreground = new SolidColorBrush(Colors.Black);
            }
            catch(Exception EX)
            {
                MessageBox.Show(EX.ToString());
            }

        }

        public void cLocalidad_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (chMismoDom.IsChecked == true)
                cLocalidadEnt.SelectedIndex = ((ComboBox)sender).SelectedIndex;
        }

        public void lblGuardar_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            getSepomex();
        }

        virtual public bool ValidarGuardado()
        {
            bool bandera = true;

            this.liTxt.Clear();
            cargaListTextBox();
            foreach (TextBox tx in liTxt)
            {
                pintarCorrecto(tx);
            }


            if (!ValidarRFC(tRFC))
                bandera = false;
            if (tRazonSocial.Text != "")
            {
                pintarCorrecto(tRazonSocial);
            }
            else
            {
                pintarError(tRazonSocial);
                bandera = false;
            }

            if (tEmail.Text != "")
                if (!ValidarEmail(tEmail))
                    bandera = false;
            if (tMailDPV.Text != "")
                if (!ValidarEmail(tMailDPV))
                    bandera = false;
            if (tTelDPV.Text != "")
                if (!ValidarTelefono(tTelDPV))
                    bandera = false;
            if (tTelEnt.Text != "")
                if (!ValidarTelefono(tTelEnt))
                    bandera = false;
            if (tTelFiscal.Text != "")
                if (!ValidarTelefono(tTelFiscal))
                    bandera = false;

            if (chDiaCL.IsChecked == false ||
                chDiaCM.IsChecked == false ||
                chDiaCMi.IsChecked == false ||
                chDiaCJ.IsChecked == false ||
                chDiaCV.IsChecked == false ||
                chDiaCS.IsChecked == false)
            {
                brdr_diasCol.Background = new SolidColorBrush(Colors.White);
                chDiaCL.Foreground = new SolidColorBrush(Colors.Black);
                chDiaCM.Foreground = new SolidColorBrush(Colors.Black);
                chDiaCMi.Foreground = new SolidColorBrush(Colors.Black);
                chDiaCJ.Foreground = new SolidColorBrush(Colors.Black);
                chDiaCV.Foreground = new SolidColorBrush(Colors.Black);
                chDiaCS.Foreground = new SolidColorBrush(Colors.Black);
            }

            if (chMismoDom.IsChecked == true)
            {
                if (tCodigoPostal.Text != "" && tCoPoEntrega.Text != "")
                {
                    if (!ValidarCodigoPostal(tCodigoPostal))
                        bandera = false;
                }
                else
                {
                    pintarCorrecto(tCodigoPostal);
                    pintarCorrecto(tCoPoEntrega);
                }
            }
            else
            {
                if (tCodigoPostal.Text != "")
                {
                    if (!ValidarCodigoPostal(tCodigoPostal))
                        bandera = false;
                }
                else
                {
                    pintarCorrecto(tCodigoPostal);
                }
                if (tCoPoEntrega.Text != "")
                {
                    if (!ValidarCodigoPostal(tCoPoEntrega))
                        bandera = false;
                }
                else
                {
                    pintarCorrecto(tCoPoEntrega);
                }
            }
            if (!bandera)
            {
                MessageBox.Show("La solicitud no puede ser guardada. Revise y valide los campos marcados", "Atención", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return bandera;
            }
            else return bandera;
        }

        public void cColoniaDistrito_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (chMismoDom.IsChecked == true)
                cColDisEntrega.SelectedIndex = ((ComboBox)sender).SelectedIndex;
        }

        public void tCodigoPostal_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (chMismoDom.IsChecked == true)
            { tCoPoEntrega.Text = tCodigoPostal.Text; }
            TextBox txtCodPost = (TextBox)sender;
            if (txtCodPost.Text.Length > 5)
            {
                pintarError(tCodigoPostal);
            }
        }

        public void tCodigoPostal_LostFocus(object sender, RoutedEventArgs e)
        {
            DataTable dt = new DataTable();
            try
            {
                TextBox txtCol = (TextBox)sender;
                
                if (ValidarCodigoPostal(txtCol))
                {
                    dt = Sepomex.getEstadoMunicipio(txtCol.Text);
                    if (dt.Rows.Count == 0)
                    {
                        pintarError(tCodigoPostal);
                        tEstado.Text = "";
                        tDelMunicipio.Text = "";
                        cColoniaDistrito.SelectedIndex = -1;
                        cLocalidad.SelectedIndex = -1;
                        tCodigoPostal.ToolTip = "Codigo Postal Incorrecto";
                        return;
                    }
                    tEstado.Text = dt.Rows[0]["ESTADO"].ToString();
                    tDelMunicipio.Text = dt.Rows[0]["MUNICIPIO"].ToString();
                    dt = Sepomex.getLocalidad(dt.Rows[0]["ID_ESTADO"].ToString(), dt.Rows[0]["ID_MUNICIPIO"].ToString());
                    if (dt.Rows.Count != 0)
                    {
                        cargarcombos(cLocalidad, dt, "LOCALIDAD", "UNID_LOCALIDAD");
                        cLocalidad.IsEnabled = true;
                        if (chMismoDom.IsChecked == true)
                            cargarcombos(cLocalidadEnt, dt, "LOCALIDAD", "UNID_LOCALIDAD");

                        cLocalidad.SelectedIndex = 0;
                    }
                    dt = Sepomex.GetColonia(txtCol.Text);

                    if (dt.Rows.Count != 0)
                    {
                        cargarcombos(cColoniaDistrito, dt, "COLONIA", "ID_COLONIA");
                        cColoniaDistrito.IsEnabled = true;
                        if (chMismoDom.IsChecked == true)
                        {
                            tEdoEntrega.Text = tEstado.Text;
                            tDelMunEnt.Text = tDelMunicipio.Text;
                            cargarcombos(cColDisEntrega, dt, "COLONIA", "ID_COLONIA");
                            cColDisEntrega.SelectedIndex = cColoniaDistrito.SelectedIndex;
                        }
                        cColoniaDistrito.SelectedIndex = 0;
                    }
                    pintarCorrecto(tCodigoPostal);
                    
                    tCodigoPostal.ToolTip = null;
                    tCoPoEntrega.ToolTip = null;
                }
                else
                {
                    pintarError(tCodigoPostal);
                    tEstado.Text = "";
                    tDelMunicipio.Text = "";
                    cColoniaDistrito.SelectedIndex = -1;
                    cLocalidad.SelectedIndex = -1;
                    cargarcombos(cColoniaDistrito, null, "", "");
                    cargarcombos(cLocalidad, null, "", "");
                    tCodigoPostal.ToolTip = "Codigo Postal Incorrecto";
                    cLocalidad.IsEnabled = false;
                    cColoniaDistrito.IsEnabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        public void tCoPoEntrega_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                DataTable dt;
                TextBox txtCol = (TextBox)sender;
                if (ValidarCodigoPostal(txtCol))
                {
                    dt = Sepomex.getEstadoMunicipio(txtCol.Text);
                    if (dt.Rows.Count == 0)
                    {
                        pintarError(tCoPoEntrega);
                        tEdoEntrega.Text = "";
                        tDelMunEnt.Text = "";
                        cColDisEntrega.SelectedIndex = -1;
                        tCoPoEntrega.ToolTip = "Codigo Postal Incorrecto";
                        return;
                    }

                    tEdoEntrega.Text = dt.Rows[0]["ESTADO"].ToString();
                    tDelMunEnt.Text = dt.Rows[0]["MUNICIPIO"].ToString();

                    dt = Sepomex.getLocalidad(dt.Rows[0]["ID_ESTADO"].ToString(), dt.Rows[0]["ID_MUNICIPIO"].ToString());
                    if (dt.Rows.Count != 0)
                    {
                        cargarcombos(cLocalidadEnt, dt, "LOCALIDAD", "UNID_LOCALIDAD");
                        cLocalidadEnt.IsEnabled = true;
                        cLocalidadEnt.SelectedIndex = 0;
                    }
                    dt = Sepomex.GetColonia(txtCol.Text);

                    if (dt.Rows.Count != 0)
                    {
                        cargarcombos(cColDisEntrega, dt, "COLONIA", "ID_COLONIA");
                        cColDisEntrega.IsEnabled = true;
                        cColDisEntrega.SelectedIndex = 0;
                    }

                   pintarCorrecto(tCoPoEntrega);
                    tCoPoEntrega.ToolTip = null;
                }
                else
                {
                    pintarError(tCoPoEntrega);
                    tEdoEntrega.Text ="";
                    tDelMunEnt.Text = "";
                    cColDisEntrega.SelectedIndex = -1;
                    cLocalidadEnt.SelectedIndex = -1;
                    cargarcombos(cColDisEntrega, null, "", "");
                    cargarcombos(cLocalidadEnt, null, "", "");
                    tCoPoEntrega.ToolTip = "Codigo Postal Incorrecto";
                    cColDisEntrega.IsEnabled = false;
                    cLocalidadEnt.IsEnabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
                
        }

        public void cTipoNegocios_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                DataTable dt;
                dt = Zona.GetData(cTipoNegocios.SelectedValue.ToString());
                if (dt.Rows.Count != 0)
                    lbl_GrupoPrecios.Content = dt.Rows[0][cZona.Text.ToString().Trim()].ToString();

                dt = Clientes4.GetData(cTipoNegocios.SelectedValue.ToString());
                if (dt.Rows.Count != 0)
                {
                    cGrupoClientes4.SelectedValue = dt.Rows[0]["ID_GRUPOCLIENTES4"].ToString();
                    cGrupoClientes4.IsEnabled = false;
                }
                else
                {
                    cGrupoClientes4.IsEnabled = true;
                    cGrupoClientes4.SelectedIndex = 0;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR cmbTipNeg: " + ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public void cCenLog_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataTable dt;
            try
            {
                tNoClo.Text=((DataRowView)((ComboBox)sender).SelectedItem).Row["Codigo"].ToString();
                dt = Clo.GetData(System.Convert.ToInt32(((DataRowView)((ComboBox)sender).SelectedItem).Row["ID_CLO"].ToString()));
                cZona.SelectionChanged -= new SelectionChangedEventHandler(cZona_SelectionChanged);
                cZona.ItemsSource = null;
                cargarcombos(cZona, dt, "DSC_ZONA", "ID_ZONA");
                cZona.SelectedIndex = 0;
                dt = getIva.GetIva(cZona.SelectedValue.ToString());
                tIVA.Text = dt.Rows[0]["IVA_VAL"].ToString();
                tIVA.IsEnabled = false;
                dt = Zona.GetData(cTipoNegocios.SelectedValue.ToString());
                if (dt.Rows.Count != 0)
                    lbl_GrupoPrecios.Content = dt.Rows[0][cZona.Text.ToString()].ToString();
                cZona.SelectionChanged += new SelectionChangedEventHandler(cZona_SelectionChanged);
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR cmbClo: " + ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

       
       public void cZona_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                DataTable dt = getIva.GetIva(cZona.SelectedValue.ToString());
                tIVA.Text = dt.Rows[0]["IVA_VAL"].ToString();
                tIVA.IsEnabled = false;
                dt = Zona.GetData(cTipoNegocios.SelectedValue.ToString());
                if (dt.Rows.Count != 0)
                    lbl_GrupoPrecios.Content = dt.Rows[0][cZona.Text.ToString()].ToString();
            }
            catch(Exception ex)
            {
                MessageBox.Show("Error cmbZona: " + ex.ToString(), "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }


       public  void cTipoSolicitud_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {          
           string v;
           bool _tiposol = false; ;
            if (ft == 1)
            {
                //string pasado = e.RemovedItems[1].ToString();
                if (!validaArchivos())
                    if (MessageBox.Show("Esta Operación eliminará los archivos ya guardados que no coincidan con la regla ¿Desea continuar?", "Cambio de Regla", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.No)
                        _tiposol = true;

                if(!_tiposol)
                {
                    this.llamarArchivos(Convert.ToInt32(lbl_idTipo.Content), cTipoSolicitud.SelectedValue.ToString(), cPersona.SelectedValue.ToString());                   
                }
                else
                {
                    cTipoSolicitud.SelectionChanged -= new SelectionChangedEventHandler(cTipoSolicitud_SelectionChanged);
                    cTipoSolicitud.SelectedValue = ctiposol;
                    cTipoSolicitud.SelectionChanged += new SelectionChangedEventHandler(cTipoSolicitud_SelectionChanged);
                    return;
                }
            }

            else
            {
                if (cPersona.IsLoaded == true)
                    {
                        this.llamarArchivos(Convert.ToInt32(lbl_idTipo.Content), cTipoSolicitud.SelectedValue.ToString(), cPersona.SelectedValue.ToString());
                     }
             }
           }


       virtual public void lblGuardar_MouseUp(object sender, MouseButtonEventArgs e)
       {

           MainWindow mw = (MainWindow)App.Current.MainWindow;
           
           if (!spAlta.IsEnabled)
           {
               MessageBox.Show("La solicitud se encuentra en un estatus distinto de Borrador, no es posible editarla.\n",
                   "Mensaje del Sistema", MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK, MessageBoxOptions.DefaultDesktopOnly);
               return;
           }

           //----------------------------------
           
           sol = GetDatatoSave(sender);

           
           ThreadUI.pnl = PanelAccion;
           
           DispatcherOperation op2 = mw.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
           ThreadUI.start(sol, mw, (((Image)sender).Name == "img_GuardarYSalir"))));
           
           //---------------------------------

           //if (((Image)sender).Name == "img_GuardarYSalir")
           //    lblGuardarYSalir_MouseDown(sender, e);

       }//end lblGuardar_MouseUp


       virtual public void cPersona_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            bool _Persona=false;
            if (ft == 1)
            {
                if (!validaArchivos())
                    if(MessageBox.Show("Esta Operación eliminará los archivos ya guardados que no coincidan con la regla ¿Desea continuar?", "Cambio de Regla", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.No)
                        _Persona = true;
                if (!_Persona)
                {
                    this.llamarArchivos(Convert.ToInt32(lbl_idTipo.Content), cTipoSolicitud.SelectedValue.ToString(), cPersona.SelectedValue.ToString());
                    setLengthRFC();
                }
                else
                {
                    cPersona.SelectionChanged -= new SelectionChangedEventHandler(cPersona_SelectionChanged);
                    cPersona.SelectedValue = cperso;
                    cPersona.SelectionChanged += new SelectionChangedEventHandler(cPersona_SelectionChanged);
                    return;
                }
            }
            else
            { this.llamarArchivos(Convert.ToInt32(lbl_idTipo.Content), cTipoSolicitud.SelectedValue.ToString(), cPersona.SelectedValue.ToString()); }
        }

        #region Copiar datos de Dir Fiscal a Dir Entrega
        public void tTelFiscal_TextChanged(object sender, TextChangedEventArgs e)
        {
            if(chMismoDom.IsChecked==true)
            {
                tTelEnt.Text=tTelFiscal.Text;
            }
        }

        public void tLada_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (chMismoDom.IsChecked == true)
            {
                tLadaEntrega.Text = tLada.Text;
            }
        }

        public void tNoInterior_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (chMismoDom.IsChecked == true)
            { tNoInEntrega.Text = tNoInterior.Text; }
        }

        public void tNoExterior_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (chMismoDom.IsChecked == true)
            { tNoExtEntrega.Text = tNoExterior.Text; }
        }

        public void tCalle_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (chMismoDom.IsChecked == true)
            { tCalleEntrega.Text = tCalle.Text; }
        }
        #endregion


        //---------Copia inmediatamente los datos de Dir Fiscal a Dir de Entrega----------/
       public void chMismoDom_Click(object sender, RoutedEventArgs e)
        {
           bool _mismodom = false; ;
            if (ft == 1)
            {
                if (!validaArchivos())
                    if (MessageBox.Show("Esta Operación eliminará los archivos ya guardados que no coincidan con la regla ¿Desea continuar?", "Cambio de Regla", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.No)
                        _mismodom = true;

                if(!_mismodom)
                {
                    if (chMismoDom.IsChecked == true)
                    {
                        tCalleEntrega.Text = tCalle.Text;
                        tNoExtEntrega.Text = tNoExterior.Text;
                        tNoInEntrega.Text = tNoInterior.Text;
                        tCoPoEntrega.Text = tCodigoPostal.Text;
                        tEdoEntrega.Text = tEstado.Text;
                        tDelMunEnt.Text = tDelMunicipio.Text;

                        tLadaEntrega.Text = tLada.Text;
                        tTelEnt.Text = tTelFiscal.Text;

                        tbFaxEnt.Text = tbFaxFiscal.Text;
                        tbFaxExtEntrega.Text = tbFaxExtFiscal.Text ;
                        tbTelExtEntrega.Text = tbTelExtFiscal.Text;

                        DataTable dt = Sepomex.GetColonia(tCoPoEntrega.Text);

                        cargarcombos(cColDisEntrega, dt, "COLONIA", "ID_COLONIA");
                        cColDisEntrega.SelectedIndex = cColoniaDistrito.SelectedIndex;

                        dt= Sepomex.getEstadoMunicipio(tCodigoPostal.Text);
                        if(dt.Rows.Count!=0)
                        {
                            dt = Sepomex.getLocalidad(dt.Rows[0]["ID_ESTADO"].ToString(), dt.Rows[0]["ID_MUNICIPIO"].ToString());
                            cargarcombos(cLocalidadEnt, dt, "LOCALIDAD", "UNID_LOCALIDAD");
                            cLocalidadEnt.SelectedIndex = cLocalidad.SelectedIndex;
                        }

                        gdDirEntrega.Background = new SolidColorBrush(Colors.Gainsboro);
                        gdDirEntrega.IsEnabled = false;
                    }

                    else
                    {
                        gdDirEntrega.Background = new SolidColorBrush(Colors.White);
                        gdDirEntrega.IsEnabled = true;
                    }

                    llamarArchivos(Convert.ToInt32(lbl_idTipo.Content), cTipoSolicitud.SelectedValue.ToString(), cPersona.SelectedValue.ToString());
                }
                else
                {
                    chMismoDom.Click -= new RoutedEventHandler(chMismoDom_Click);
                    chMismoDom.IsChecked = !((CheckBox)sender).IsChecked;
                    chMismoDom.Click += new RoutedEventHandler(chMismoDom_Click);
                }

            }
        }


       public void chOtrosClientes_Click(object sender, RoutedEventArgs e)
       {
          
           if ((bool)chOtrosClientes.IsChecked)
               cTerritorio.IsEnabled = true;
           else
           {
               DataTable dt;
               ObtieneRespVentas fvtas = new ObtieneRespVentas();
               cTerritorio.IsEnabled = false;
               dt = Estructura.GetData(5, fvtas.IdTerritorio);
               cTerritorio.SelectedValue = dt.Rows[0][0].ToString();
           }

           //DataTable dt;
           //ObtieneRespVentas fvtas = new ObtieneRespVentas();
           //if ((bool)chOtrosClientes.IsChecked)
           //    dt = Estructura.GetData(5, "null");
           //else
           //    dt = Estructura.GetData(5, fvtas.IdTerritorio);

           //cTerritorio.IsEnabled = (bool)chOtrosClientes.IsChecked;
           //cargarcombos(cTerritorio, dt, "DSC_ESTRUCTURA", "ID_CODIGO");

           //cTerritorio_SelectionChanged(null, null);

       }


       public void cClaveBanco_SelectionChanged(object sender, SelectionChangedEventArgs e)
       {
           DataTable dt = Banco.GetData();
           if (dt == null)
           {
               return;
           }

           if (cClaveBanco.SelectedIndex > -1)
           {
               lbNomBanco.Content = dt.Rows[cClaveBanco.SelectedIndex]["DSC_BANCO"].ToString();
           }
           else
           { lbNomBanco.Content = dt.Rows[0]["DSC_BANCO"].ToString(); }
          
       }


       public void cTerritorio_SelectionChanged(object sender, SelectionChangedEventArgs e)
       {
           if (cTerritorio.SelectedIndex > -1)
           {
               DataRowView cbi = (DataRowView)cTerritorio.SelectedItem;

               string prueba =  cbi.Row["ID_CODIGO"].ToString();
               
               DataTable dt = Estructura.GetData(2, cbi.Row[0].ToString());
               if(dt.Rows.Count!=0) tSubdir.Text = dt.Rows[0]["DSC_ESTRUCTURA"].ToString();

               DataTable dt2 = Estructura.GetData(3, cbi.Row[0].ToString());

               tGerencia.Text = dt2.Rows[0]["DSC_ESTRUCTURA"].ToString();
           }
          
       }
              
        
        /// <summary>
        /// Cargar combos con sus respectivos items, Si envia nullo vacia el combo
        /// </summary>
        /// <param name="cb">Combo</param>
        /// <param name="dt">DataContent</param>
        /// <param name="member">MemberPath</param>
        /// <param name="value">MemberValuePath</param>
        public void cargarcombos(ComboBox cb, DataTable dt, string member, string value)
        {             
            if (dt == null)
            {
                cb.DataContext = null;
                cb.DisplayMemberPath = null;
                cb.SelectedValuePath = null;
                return;
            }

        
                cb.ItemsSource = ((IListSource)dt).GetList();
                cb.DataContext = dt;
                cb.DisplayMemberPath = member;
                cb.SelectedValuePath = value;
           

            if (cb.Items != null)
            {
                cb.SelectedIndex = 0;
            }
                      
        }

     
                
        //-----------------Funcion que llena textbox Estado----------------//
        public void cargartextos(TextBox tbestado, DataTable dt)
        {
            if (dt == null)
            {
                return;
            }

            tbestado.Text = dt.Rows[0]["ESTADO"].ToString();

        }
        

        //--------Botón Cancelar las solicitud, Panel de Acción-----------//
        public void bdCancelar_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (ValidarCerradoSolicitud())
            {
                PanelCentral.Content = null;//SaveFiles.solicitudCancelada(sSolicitudDocs); 
                Sol.UISolicitudes Despliega = new Sol.UISolicitudes(PanelAccion, PanelNavegacion, PanelCentral);
            }
            else
                return;
        }



        //-----Botón Archivos de Panel de Acción------
        public void bdArchivos_MouseUp(object sender, MouseButtonEventArgs e)
        {
           //Aquí llama a la función que despliega en el popup la lista de archivos
            popArchivos.PlacementTarget = (Image)sender;
            popArchivos.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
            popArchivos.IsOpen = true;
        }


              //-----------Llenar lista de archivos------------//
        public void llamarArchivos(int tipoSolicitud, string tipoSolicitante, string tipoPersona)
        {
            DataSet dsDatasDocs = new DataSet();
            Boolean banderaCambios = false;
            //primerArchivo = "-1";
            try
            {
                if (chMismoDom.IsChecked == true)
                { mismodomi = 1; }
                else
                { mismodomi = 0; }
               DataTable dt = CargarArchivos.GetArchivos(tipoSolicitud, tipoSolicitante, CheckMismoDomicilio, tipoPersona);

               #region si  dt nulo
               if (dt == null)
               {
                   //Despliega no hay archivos por estar vacío                   
                   StackPanel spN = new StackPanel();
                   TextBlock nTxtB = new TextBlock();
                   nTxtB.Text = "No hay archivos";
                   spN.Children.Add(nTxtB);
                   spArchivos.Children.Add(spN);
                   return;
               }
               #endregion

               else  //si hay archivos
               {

                   if (ft == 0)
                   {
                       DocsNuevos(dt,true);
                       
                       // ft = 1;

                   }//final if ft=0
                   else //ft =1
                   {
                       cperso = cPersona.SelectedValue.ToString();
                       ctiposol = cTipoSolicitud.SelectedValue.ToString();

                       if (chMismoDom.IsChecked == true)
                           check = 1;
                       else 
                           check = 0; 

                       //--- Muestra el botón Archivos----//
                       bdArchivos.Opacity = 1;

                       dsDatasDocs= DataSinDocExistentes(dt);
                       
                       DocsSeQuedan(dsDatasDocs.Tables[2],ref banderaCambios);

                       //if(dsDatasDocs.Tables[1].Rows.Count!=0)
                           DocsNuevos(dsDatasDocs.Tables[1],banderaCambios);

                       //Region de agregar nuevos Docs
                       if (dt.Rows.Count != 0)
                       {
                           if (spArchivos.Children.Count == 0)
                           {
                               ft = 0;
                               llamarArchivos(tipoSolicitud, tipoSolicitante, tipoPersona);
                           }
                           else
                           {
                               DataSet dsSinExistentes = DataSinDocExistentes(dt);
                           }
                       }//ENDIF

                   }//final else ft=1
                } //Fin del else (sí hay archivos)
                ft = 1;
            }//---final try


            catch (Exception e)
            {
                MessageBox.Show("No se pudo mostrar  " + e, "Error");
            }
        
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tipoSolicitud"></param>
        /// <param name="tipoSolicitante"></param>
        /// <param name="tipoPersona"></param>
        /// <param name="blocked">Para modificacion exclusivamente</param>
        public void llamarArchivos(int tipoSolicitud, string tipoSolicitante, string tipoPersona,int blocked)
        {
            DataSet dsDatasDocs = new DataSet();
            Boolean banderaCambios = false;
            //primerArchivo = "-1";
            try
            {
                if (chMismoDom.IsChecked == true)
                { mismodomi = 1; }
                else
                { mismodomi = 0; }
                DataTable dt = CargarArchivos.GetArchivos(tipoSolicitud, tipoSolicitante, CheckMismoDomicilio, tipoPersona,blocked);

                #region si  dt nulo
                if (dt == null)
                {
                    //Despliega no hay archivos por estar vacío                   
                    StackPanel spN = new StackPanel();
                    TextBlock nTxtB = new TextBlock();
                    nTxtB.Text = "No hay archivos";
                    spN.Children.Add(nTxtB);
                    spArchivos.Children.Add(spN);
                    return;
                }
                #endregion

                else  //si hay archivos
                {

                    if (ft == 0)
                    {
                        DocsNuevos(dt, true);

                        // ft = 1;

                    }//final if ft=0
                    else //ft =1
                    {
                        cperso = cPersona.SelectedValue.ToString();
                        ctiposol = cTipoSolicitud.SelectedValue.ToString();

                        if (chMismoDom.IsChecked == true)
                            check = 1;
                        else
                            check = 0;

                        //--- Muestra el botón Archivos----//
                        bdArchivos.Opacity = 1;

                        dsDatasDocs = DataSinDocExistentes(dt);

                        DocsSeQuedan(dsDatasDocs.Tables[2], ref banderaCambios);

                        //if(dsDatasDocs.Tables[1].Rows.Count!=0)
                        DocsNuevos(dsDatasDocs.Tables[1], banderaCambios);

                        //Region de agregar nuevos Docs
                        if (dt.Rows.Count != 0)
                        {
                            if (spArchivos.Children.Count == 0)
                            {
                                ft = 0;
                                llamarArchivos(tipoSolicitud, tipoSolicitante, tipoPersona);
                            }
                            else
                            {
                                DataSet dsSinExistentes = DataSinDocExistentes(dt);
                            }
                        }//ENDIF

                    }//final else ft=1
                } //Fin del else (sí hay archivos)
                ft = 1;
            }//---final try


            catch (Exception e)
            {
                MessageBox.Show("No se pudo mostrar  " + e, "Error");
            }

        }

        private void DocsNuevos(DataTable dataTable,Boolean banderaCambios)
        {
            string fileName;
            string sourcePath;
            string sourceFile;
            string destFile;
            string extension;
            string tamanio;

            int indice = 0;

            StackPanel stkPanDoc;
            DockPanel dockPan;
            TextBlock txtBlockTipoDocLetra;
            TextBlock txtBlockCnfDoc;
            TextBlock txtBlockRuleDoc;
            TextBlock txtBlockUnidSol;
            TextBlock txtBlockUnidDoc;
            TextBlock txtBlockPathDoc;
            TextBlock txtBlockNomGene;
            TextBlock txtBlockLinkButton1;
            TextBlock txtBlockLinkButton2;

            Border _brdr = new Border();
            Thickness thick = new Thickness();
            thick.Top = 5;
            DataTable dtbUpsertArchivo;
            BitmapImage bi2;
            FileInfo file;

            Image imgEstatus;

            Label lbl_Ext;
            //Image imagen;
            try
            {
                if (dataTable.Rows.Count == 0)
                {
                    if (banderaCambios)
                    {
                        bdArchivos.IsEnabled = false;
                        bdArchivos.Opacity = 0.5;
                    }
                }
                else
                {
                    bdArchivos.IsEnabled = true;
                    bdArchivos.Opacity = 1.0;
                    foreach (DataRow dr in dataTable.Rows)
                    {
                        _brdr = new Border();
                        _brdr.BorderBrush = Brushes.LightGray;
                        _brdr.BorderThickness = new Thickness(0, 0, 0, 1);

                        dockPan = new DockPanel();
                        dockPan.LastChildFill = false;
                        txtBlockLinkButton1 = new TextBlock();
                        txtBlockLinkButton1.TextDecorations = TextDecorations.Underline;
                        txtBlockLinkButton1.Foreground = new SolidColorBrush(Colors.Blue);
                        DockPanel.SetDock(txtBlockLinkButton1, Dock.Right);
                        txtBlockLinkButton1.Text = "Adjuntar";
                        txtBlockLinkButton1.Width = 50;
                        txtBlockLinkButton1.Name = "AdjAbr";
                        txtBlockLinkButton1.Cursor = Cursors.Hand;
                        txtBlockLinkButton1.Margin = new Thickness(5);
                        txtBlockLinkButton1.MouseEnter += delegate(object obj1, MouseEventArgs x)
                        { txtBlockLinkButton1_MouseEnter(obj1, x); };
                        txtBlockLinkButton1.MouseLeave += delegate(object obj1, MouseEventArgs x)
                        { txtBlockLinkButton_MouseLeave(obj1, x); };

                        txtBlockLinkButton2 = new TextBlock();
                        txtBlockLinkButton2.TextDecorations = TextDecorations.Underline;
                        txtBlockLinkButton2.Foreground = new SolidColorBrush(Colors.Blue);
                        DockPanel.SetDock(txtBlockLinkButton2, Dock.Right);
                        txtBlockLinkButton2.Text = "Eliminar";
                        txtBlockLinkButton2.Name = "Eliminar";
                        txtBlockLinkButton2.Cursor = Cursors.Hand;
                        txtBlockLinkButton2.IsEnabled = false;
                        txtBlockLinkButton2.Foreground = Brushes.Silver;
                        txtBlockLinkButton2.Margin = new Thickness(5);
                        txtBlockLinkButton2.MouseEnter += delegate(object obj1, MouseEventArgs x)
                        { txtBlockLinkButton1_MouseEnter(obj1, x); };
                        txtBlockLinkButton2.MouseLeave += delegate(object obj1, MouseEventArgs x)
                        { txtBlockLinkButton_MouseLeave(obj1, x); };

                        lbl_Ext = new Label();
                        stkPanDoc = new StackPanel();

                        stkPanDoc.Orientation = Orientation.Horizontal;
                        stkPanDoc.Height = 30;
                        txtBlockTipoDocLetra = new TextBlock();
                        txtBlockCnfDoc = new TextBlock();
                        txtBlockRuleDoc = new TextBlock();
                        txtBlockUnidSol = new TextBlock();
                        txtBlockPathDoc = new TextBlock();
                        txtBlockUnidDoc = new TextBlock();
                        txtBlockNomGene = new TextBlock();

                        txtBlockUnidSol.Name = "UnidSol";
                        txtBlockUnidSol.Visibility = Visibility.Collapsed;
                        txtBlockUnidSol.Text = "-1";

                        txtBlockPathDoc.Name = "Path";
                        txtBlockPathDoc.Text = "";
                        lbl_Ext.Content = dataTable.Rows[indice]["TYPE_DOC"].ToString();
                        txtBlockPathDoc.Tag = lbl_Ext;
                        txtBlockPathDoc.Visibility = Visibility.Collapsed;

                        txtBlockUnidDoc.Name = "UnidDoc";
                        txtBlockUnidDoc.Text = "-1";
                        txtBlockUnidDoc.Visibility = Visibility.Collapsed;

                        txtBlockTipoDocLetra.Name = "Documento";
                        txtBlockTipoDocLetra.Text = dataTable.Rows[indice]["DOCUMENTO"].ToString();
                        txtBlockTipoDocLetra.Margin = new Thickness(5);
                        txtBlockTipoDocLetra.HorizontalAlignment = HorizontalAlignment.Left;

                        txtBlockCnfDoc.Name = "CnfDoc";
                        txtBlockCnfDoc.Text = dataTable.Rows[indice]["UNID_CNF_DOCUMENTO"].ToString();
                        txtBlockCnfDoc.Visibility = Visibility.Collapsed;

                        txtBlockRuleDoc.Name = "unidRuleDoc";
                        txtBlockRuleDoc.Text = dataTable.Rows[indice]["UNID_CNF_RULEDOC"].ToString();
                        txtBlockRuleDoc.Visibility = Visibility.Collapsed;

                        txtBlockNomGene.Name = "nomGene";
                        txtBlockNomGene.Visibility = Visibility.Collapsed;
                        txtBlockNomGene.Text = "";

                        imgEstatus = new Image();
                        imgEstatus.Stretch = Stretch.Fill;
                        imgEstatus.Name = "imagen";
                        imgEstatus.Source = iconoNoCargado();
                        imgEstatus.Margin = new Thickness(9);
                        imgEstatus.Height = 10;
                        imgEstatus.Width = 10;
                        imgEstatus.HorizontalAlignment = HorizontalAlignment.Left;

                        _brdr.Child = dockPan;

                        dockPan.Children.Add(imgEstatus);
                        dockPan.Children.Add(txtBlockTipoDocLetra);
                        dockPan.Children.Add(txtBlockLinkButton2);
                        dockPan.Children.Add(borderDocs());
                        dockPan.Children.Add(txtBlockLinkButton1);
                        dockPan.Children.Add(borderDocs());
                        dockPan.Children.Add(txtBlockPathDoc);
                        dockPan.Children.Add(txtBlockCnfDoc);
                        dockPan.Children.Add(txtBlockRuleDoc);
                        dockPan.Children.Add(txtBlockUnidSol);
                        dockPan.Children.Add(txtBlockUnidDoc);
                        dockPan.Children.Add(txtBlockNomGene);

                        spArchivos.Children.Add(_brdr);

                        ft = 1;

                        //Llena la Regla actual 
                        Regladoc = dataTable.Rows[indice]["UNID_CNF_RULEDOC"].ToString();

                        indice += 1;
                        #region Borrar Archivo al Click en textblock
                        txtBlockLinkButton2.MouseUp += delegate(object sender4, MouseButtonEventArgs e4)
                        {
                            txtBlockLinkButton2 = (TextBlock)sender4;
                            DockPanel stkPanHijoDoc = (DockPanel)txtBlockLinkButton2.Parent;
                            foreach (var child4 in stkPanHijoDoc.Children)
                            {
                                if (child4.GetType() == typeof(System.Windows.Controls.TextBlock))
                                    switch (((TextBlock)child4).Name.ToString())
                                    {
                                        case "nomGene":
                                            txtBlockNomGene = (TextBlock)child4;
                                            break;

                                        case "Path":
                                            txtBlockPathDoc = (TextBlock)child4;
                                            break;

                                        case "Documento":
                                            txtBlockTipoDocLetra = (TextBlock)child4;
                                            break;

                                        case "AdjAbr":
                                            txtBlockLinkButton1 = (TextBlock)child4;
                                            break;

                                        case "UnidSol":
                                            txtBlockUnidSol = (TextBlock)child4;
                                            break;

                                        case "UnidDoc":
                                            txtBlockUnidDoc = (TextBlock)child4;
                                            break;
                                    }
                                if (child4.GetType() == typeof(System.Windows.Controls.Image))
                                    imgEstatus = (Image)child4;
                            }

                            if (txtBlockPathDoc.Text != "")
                                if (MessageBox.Show("¿Desea eliminar archivo?", "Eliminar", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                                {
                                    bi2 = new BitmapImage();
                                    bi2.BeginInit();
                                    bi2.UriSource = new Uri("Images/icon_cancelar_001.png", UriKind.Relative);
                                    bi2.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                                    bi2.EndInit();
                                    imgEstatus.Stretch = Stretch.Fill;
                                    imgEstatus.Source = bi2;
                                    imgEstatus.Margin = new Thickness(9);
                                    imgEstatus.Height = 10;
                                    imgEstatus.Width = 10;
                                    imgEstatus.HorizontalAlignment = HorizontalAlignment.Left;

                                    //eliminar archivo de la base de datos
                                    SaveFiles.fueraDeRegla(txtBlockUnidSol.Text, txtBlockUnidDoc.Text);
                                    if (!File.Exists(txtBlockPathDoc.Text))
                                        MessageBox.Show("El archivo no existe", "Archivo No encontrado", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                                    else
                                        File.Delete(txtBlockPathDoc.Text);

                                    txtBlockPathDoc.Text = null;
                                    txtBlockNomGene.Text = null;
                                    txtBlockLinkButton2.IsEnabled = false;
                                    txtBlockLinkButton2.Foreground = Brushes.Silver;
                                    txtBlockLinkButton1.Text = "Adjuntar";
                                }
                        };
                        #endregion

                        #region abrir archivo al dar click en el textblock
                        txtBlockLinkButton1.MouseUp += delegate(object sender3, MouseButtonEventArgs e3)
                        {
                            txtBlockLinkButton1 = (TextBlock)sender3;
                            DockPanel stkPanHijoDoc = (DockPanel)txtBlockLinkButton1.Parent;
                            foreach (var child4 in stkPanHijoDoc.Children)
                            {
                                if (child4.GetType() == typeof(System.Windows.Controls.TextBlock))
                                    switch (((TextBlock)child4).Name.ToString())
                                    {
                                        case "UnidSol":
                                            txtBlockUnidSol = (TextBlock)child4;
                                            break;

                                        case "UnidDoc":
                                            txtBlockUnidDoc = (TextBlock)child4;
                                            break;

                                        case "unidRuleDoc":
                                            txtBlockRuleDoc = (TextBlock)child4;
                                            break;

                                        case "CnfDoc":
                                            txtBlockCnfDoc = (TextBlock)child4;
                                            break;

                                        case "nomGene":
                                            txtBlockNomGene = (TextBlock)child4;
                                            break;

                                        case "Path":
                                            txtBlockPathDoc = (TextBlock)child4;
                                            break;

                                        case "Documento":
                                            txtBlockTipoDocLetra = (TextBlock)child4;
                                            break;

                                        case "Eliminar":
                                            txtBlockLinkButton2 = (TextBlock)child4;
                                            break;
                                    }
                                if (child4.GetType() == typeof(System.Windows.Controls.Image))
                                    imgEstatus = (Image)child4;
                            }

                            if (txtBlockNomGene.Text == "")
                            {

                                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                                dlg.Multiselect = false;
                                dlg.DefaultExt = ((Label)txtBlockPathDoc.Tag).Content.ToString();
                                dlg.Filter = "Archivo " + txtBlockTipoDocLetra.Text.ToString() + "|*" + ((Label)txtBlockPathDoc.Tag).Content.ToString() +
                                    "|Todos los Archivos|*.*";
                                Nullable<bool> result = dlg.ShowDialog();

                                #region Archivo Adjunto
                                if (result == true)
                                {
                                    fileName = dlg.SafeFileName;
                                    sourcePath = System.IO.Path.GetDirectoryName(dlg.FileName);
                                    sourceFile = System.IO.Path.Combine(sourcePath, fileName);
                                    destFile = System.IO.Path.Combine(targetPath, fileName);
                                    dtbUpsertArchivo = SaveFiles.InsertArchivos(sSolicitudDocs, txtBlockUnidDoc.Text, txtBlockRuleDoc.Text,
                                                       txtBlockCnfDoc.Text, System.IO.Path.GetFileNameWithoutExtension(txtBlockNomGene.Text).ToString(), fileName);

                                    txtBlockUnidSol.Text = dtbUpsertArchivo.Rows[0][0].ToString();
                                    sSolicitudDocs = dtbUpsertArchivo.Rows[0][0].ToString();
                                    txtBlockUnidDoc.Text = dtbUpsertArchivo.Rows[0][1].ToString();
                                    txtBlockRuleDoc.Text = dtbUpsertArchivo.Rows[0][2].ToString();
                                    txtBlockCnfDoc.Text = dtbUpsertArchivo.Rows[0][3].ToString();
                                    txtBlockNomGene.Text = System.IO.Path.GetFileNameWithoutExtension(dtbUpsertArchivo.Rows[0][4].ToString());

                                    fileName = dtbUpsertArchivo.Rows[0][4].ToString();
                                    destFile = System.IO.Path.Combine(targetPath, fileName);

                                    System.IO.File.Copy(sourceFile, destFile, true);
                                    extension = System.IO.Path.GetExtension(destFile);

                                    file = new FileInfo(destFile);
                                    tamanio = Convert.ToString(file.Length / 1024);

                                    txtBlockPathDoc.Text = destFile;

                                    BitmapImage bi1 = new BitmapImage();
                                    bi1.CacheOption = BitmapCacheOption.OnLoad;
                                    bi1.BeginInit();
                                    bi1.UriSource = new Uri("Images/icon_validar_001.png", UriKind.Relative);
                                    bi1.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                                    bi1.EndInit();
                                    imgEstatus.Stretch = Stretch.Fill;
                                    imgEstatus.Source = bi1;
                                    imgEstatus.Margin = new Thickness(9);
                                    imgEstatus.Height = 10;
                                    imgEstatus.Width = 10;
                                    imgEstatus.HorizontalAlignment = HorizontalAlignment.Left;
                                    txtBlockLinkButton1.Text = "Abrir";
                                    txtBlockLinkButton2.IsEnabled = true;
                                    txtBlockLinkButton2.Foreground = Brushes.Blue;
                                }
                            }
                                #endregion

                            else
                            {
                                if (txtBlockPathDoc.Text == null || txtBlockPathDoc.Text == "")
                                    MessageBox.Show("Aun no cargado algún archivo", "Abrir Archivo", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                                else
                                {
                                    if (!File.Exists(txtBlockPathDoc.Text))
                                    {
                                        MessageBox.Show("El archivo no existe", "Archivo No encontrado", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                                        bi2 = new BitmapImage();
                                        bi2.BeginInit();
                                        bi2.UriSource = new Uri("Images/icon_cancelar_001.png", UriKind.Relative);
                                        bi2.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                                        bi2.EndInit();
                                        imgEstatus.Stretch = Stretch.Fill;
                                        imgEstatus.Source = bi2;
                                        imgEstatus.Margin = new Thickness(9);
                                        imgEstatus.Height = 10;
                                        imgEstatus.Width = 10;
                                        imgEstatus.HorizontalAlignment = HorizontalAlignment.Left;

                                        //eliminar archivo de la base de datos
                                        SaveFiles.fueraDeRegla(txtBlockUnidSol.Text, txtBlockUnidDoc.Text);
                                        txtBlockPathDoc.Text = null;
                                        txtBlockNomGene.Text = null;
                                        txtBlockLinkButton2.IsEnabled = false;
                                        txtBlockLinkButton2.Foreground = Brushes.Silver;
                                        txtBlockLinkButton1.Text = "Adjuntar";
                                        return;
                                    }
                                    System.Diagnostics.Process.Start(txtBlockPathDoc.Text, "");
                                }
                            }

                        };//Fin del clic en el textblock del archivo
                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error al cargar Documentos:" + ex.ToString(), "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void txtBlockLinkButton_MouseLeave(object obj1, MouseEventArgs x)
        {
            ((TextBlock)obj1).Foreground = Brushes.Blue;
        }

        void txtBlockLinkButton1_MouseEnter(object sender, MouseEventArgs e)
        {
            ((TextBlock)sender).Foreground = Brushes.Purple;
        }

        private UIElement borderDocs()
        {
            Border _brdr = new Border();
            _brdr.BorderBrush = Brushes.LightGray;
            _brdr.BorderThickness = new Thickness(0, 0, 1, 1);
            _brdr.HorizontalAlignment = HorizontalAlignment.Right;
            DockPanel.SetDock(_brdr, Dock.Right);
            //_brdr.Margin = new Thickness();
            _brdr.Height = 15;
            return _brdr;
        }

        private void DocsSeQuedan(DataTable dataTable, ref Boolean banderaCambios)
        {
            int existe = 0;
            string USD = "";
            string Docus = "";

            DockPanel stackhijo;
            TextBlock tbck;
            // int indexHijo = 0;

            List<Border> stkxEli = new List<Border>();
            try
            {
                foreach (var child in spArchivos.Children)
                {
                    stackhijo = (DockPanel)((Border)child).Child;

                    foreach (var tbkhijo in stackhijo.Children)
                    {
                        if (tbkhijo.GetType() == typeof(System.Windows.Controls.TextBlock))
                        {
                            tbck = (TextBlock)tbkhijo;
                            
                            if (tbck.Name == "UnidDoc")
                                USD = tbck.Text;

                            if (tbck.Name == "UnidSol")
                                Docus = tbck.Text;

                            if (tbck.Name == "CnfDoc")
                            {
                                for (int i = 0; i < dataTable.Rows.Count; i++)
                                    if (tbck.Text == dataTable.Rows[i]["UNID_CNF_DOCUMENTO"].ToString())
                                        existe = 1;

                                if (existe == 0)
                                    stkxEli.Add((Border)stackhijo.Parent);
                             }
                        }//final si es tipo textblock
                    }
                    
                    if (existe == 0)
                        if (USD != "" && Docus != "")
                        {
                            SaveFiles.fueraDeRegla(Docus, USD);
                            USD = "";
                            Docus = "";
                        }

                    existe = 0;
                } //buscar hijos en spArchivos

                for (int j = 0; j < stkxEli.Count; j++)
                {
                    //quitar los stackpanels visibles no coincidentes
                    spArchivos.Children.Remove(stkxEli[j]);
                }
                if (spArchivos.Children.Count == 0) banderaCambios = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error al borrar Documentos: " + ex.ToString(), "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }
        private DataSet DataSinDocExistentes(DataTable dt)
        {
            DataTable dtSinExistentes = new DataTable();
            DataTable dtQuedan= new DataTable();
            DockPanel stackhijo;
            TextBlock tbkhijo;
            DataRow RowABorrar;
            DataRow NuevoRow;
            NuevoRow = dtQuedan.NewRow();
            DataSet ds = new DataSet();
            try
            {
                dtQuedan = dt.Clone();
                dtSinExistentes = dt.Copy();
                string[] arreglo;
                int i=0,j=0;
                int iNumeroRows=dt.Rows.Count;
                bool entro = false;                
                ds.Tables.Add(dt.Copy());

                arreglo = new string[1];
                if (spArchivos.Children.Count != 0 || dt.Rows.Count != 0)
                    arreglo = new string[spArchivos.Children.Count + dt.Rows.Count];

                foreach (var childstack in spArchivos.Children)
                    if (childstack.GetType() == typeof(Border))
                    {
                        stackhijo = (DockPanel)((Border)childstack).Child;
                        foreach (var tbkchild in stackhijo.Children)
                            if (tbkchild.GetType() == typeof(System.Windows.Controls.TextBlock))
                            {
                                tbkhijo = (TextBlock)tbkchild;
                                if (tbkhijo.Name == "CnfDoc")
                                {
                                    entro = true;
                                    arreglo[i] = tbkhijo.Text.ToString();
                                    i += 1;
                                }
                            }
                    }

                if (entro)
                {
                    for (i = 0; i < iNumeroRows; i++)
                        for (j = 0; j < arreglo.Length; j++)
                            if (arreglo[j] != null)
                                if (arreglo[j].ToString() == dtSinExistentes.Rows[i]["UNID_CNF_DOCUMENTO"].ToString())
                                {
                                    ////NuevoRow =dtSinExistentes.Rows[i];
                                    dtQuedan.ImportRow(dtSinExistentes.Rows[i]);
                                    RowABorrar = dtSinExistentes.Rows[i];
                                    dtSinExistentes.Rows.Remove(RowABorrar);
                                    dtSinExistentes.AcceptChanges();
                                    dtQuedan.AcceptChanges();
                                    if (dtSinExistentes.Rows.Count != 0)
                                        i = 0;
                                    else
                                    {
                                        ds.Tables.Add(dtSinExistentes);
                                        ds.Tables.Add(dtQuedan);
                                        return ds;
                                    }
                                    iNumeroRows = dtSinExistentes.Rows.Count;
                                    //dtSinExistentes.Rows[i].Delete();
                                }
                }
                ds.Tables.Add(dtSinExistentes);
                ds.Tables.Add(dtQuedan);
                return ds;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return ds;
            }
            finally
            {
                dtSinExistentes = null;
                dtQuedan = null;
                stackhijo= null;
                tbkhijo= null;
                RowABorrar= null;
                ds = null;
            }
        }
        //Finbal cargar archivos

        
        public BitmapImage iconoCargado()
        {    
            Image iconoStat = new Image();
            BitmapImage bi1 = new BitmapImage();
            bi1.CacheOption = BitmapCacheOption.OnLoad;
            bi1.BeginInit();
            bi1.UriSource = new Uri("Images/icon_validar_001.png", UriKind.Relative);
            bi1.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            bi1.EndInit();
            bi1.DecodePixelHeight = 5;
            iconoStat.Stretch = Stretch.Fill;
            iconoStat.Name = "imagen";
            iconoStat.Source = bi1;
            
            return bi1;
        }

        public BitmapImage iconoNoCargado()
          {
            Image iconoStat = new Image();
            BitmapImage bi2 = new BitmapImage();
            bi2.BeginInit();
            bi2.UriSource = new Uri("Images/icon_cancelar_001.png", UriKind.Relative);
            bi2.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            bi2.EndInit();
            bi2.DecodePixelHeight = 5;
            iconoStat.Stretch = Stretch.Fill;
            iconoStat.Source = bi2;
            iconoStat.Name = "imagen";
            return bi2;
        }

    
        #region Validaciones
        public virtual bool ValidarRFC(TextBox tRFC1)
        {       
            tRFC1.Text = tRFC1.Text.ToUpper();
                if(Regex.IsMatch(tRFC1.Text,
                    (tRFC1.MaxLength == 12) ? @"^(([A-Z]){3})([0-9]{2}[0-1][0-9][0-3][0-9][A-Z,0-9]?[A-Z,0-9]?[0-9,AZ]?)" : 
                                              @"[A-Z,Ñ,&]{4}[0-9]{2}[0-1][0-9][0-3][0-9][A-Z,0-9]?[A-Z,0-9]?[0-9,AZ]?") && tRFC1.Text.Length==tRFC1.MaxLength)
                {
                    pintarCorrecto(tRFC1);
                    return true;
                }
                else
                {
                    pintarError(tRFC1);
                    return false;
                }          
        }


        public bool ValidarEmail(TextBox tEmail1)
        {
            
            string expresion = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";

                if (Regex.IsMatch(tEmail1.Text, expresion))
                {
                    if (Regex.Replace(tEmail1.Text, expresion, String.Empty).Length == 0)
                    {
                        pintarCorrecto(tEmail1);
                        return true;
                    }
                    else
                    {
                        //MessageBox.Show("Teclee un Email válido", "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
                        pintarError(tEmail1);
                        return false;
                    }
                }
                else
                {
                    //MessageBox.Show("Teclee un Email válido", "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
                    pintarError(tEmail1);
                    return false;
                }
            

        }

        public bool ValidarCodigoPostal(TextBox tCodPost)
        {
            int result;
            try
            {
                if (tCodPost.Text.Length == 5 && 
                    int.TryParse(tCodPost.Text, out result) && 
                    Convert.ToInt32(result) > 0)
                    return true;
                else
                    return false;
            }catch(Exception ex)
            {
                return false;
                throw ex;
            }
        }

        public bool ValidarTelefono(TextBox tTelefono)
        {                   
            
                String TxtBxs = tTelefono.Text;
                if (tTelefono.Text.Length > 7)
                {
                    foreach (char car in TxtBxs)
                    {
                        if (car < '0' || car > '9')
                        {
                            //MessageBox.Show("El teléfono debe incluir sólo números", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                            pintarError(tTelefono);
                            return false;
                        }

                        else {
                            pintarCorrecto(tTelefono);
                            return true;
                        }
                    }
                    return true;
                }

                else
                {
                    //MessageBox.Show("El teléfono debe incluir 8 números como mínimo", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    pintarError(tTelefono);
                    return false;
                }

        }

        public Boolean validaArchivos(out String Validacion)
        {
            DockPanel stkPanHijoDoc;
            String[] ReglaDoc;
            bool entro = false;
            TextBlock txtBlockPathDoc = new TextBlock();
            Image imgDoc = new Image();

            try
            {
                ReglaDoc= new String[spArchivos.Children.Count];
                foreach (var child1 in spArchivos.Children)
                {
                    stkPanHijoDoc = (DockPanel)((Border)child1).Child;
                    foreach (var child2 in stkPanHijoDoc.Children)
                        if (child2.GetType() == typeof(TextBlock) && ((TextBlock)child2).Name.ToString() == "Path")
                        {
                            txtBlockPathDoc = (TextBlock)child2;
                            entro = true;
                        }

                    if(entro)
                        if (!File.Exists(txtBlockPathDoc.Text))
                        {
                            Validacion = "Algún documento de la solicitud no ha sido agregado";
                            return false;
                        }
                }
                Validacion = "OK";
                if (!entro) Validacion = "No existen documentos por agregar";
                return true;
            }
            catch (Exception ex)
            {
                Validacion= "Error al validar los documentos:" + ex.ToString();
                return false;
            }
        }

        public Boolean validaArchivos()
        {
            DockPanel stkPanHijoDoc;
            String[] ReglaDoc;
            TextBlock txtBlockPathDoc = new TextBlock();
            try
            {
                ReglaDoc = new String[spArchivos.Children.Count];
                foreach (var child1 in spArchivos.Children)
                {
                    stkPanHijoDoc = (DockPanel)((Border)child1).Child;
                    foreach (var child2 in stkPanHijoDoc.Children)
                        if (child2.GetType() == typeof(TextBlock) && ((TextBlock)child2).Name.ToString() == "Path")
                            txtBlockPathDoc = (TextBlock)child2;

                    if (txtBlockPathDoc.Text != "")
                        return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// Carga los list box dependiendo en que 
        /// </summary>
        /// <param name="seccion">seccion de la solicitud a cargar en el list</param>
        /// <returns></returns>
        virtual public void cargaListTextBox()
        {
            try
            {
                //Datos Generales
                this.liTxt.Add(tRazonSocial);
                this.liTxt.Add(tRFC);
                this.liTxt.Add(tEmail);
                this.liTxt.Add(tNombreSucursal);
                this.liTxt.Add(tNumeroSucursal);

                //Direccion Fiscal
                this.liTxt.Add(tCalle);
                this.liTxt.Add(tNoExterior);
                this.liTxt.Add(tNoInterior);
                this.liTxt.Add(tbFaxFiscal);
                this.liTxt.Add(tbFaxExtFiscal);
                this.liTxt.Add(tbTelExtFiscal);
                //this.liTxt.Add(tEstado);
                //this.liTxt.Add(tDelMunicipio);
                this.liTxt.Add(tLada);
                this.liTxt.Add(tTelFiscal);

                //Direccion Entrega
                this.liTxt.Add(tCalleEntrega);
                this.liTxt.Add(tNoExtEntrega);
                this.liTxt.Add(tNoInEntrega);
                this.liTxt.Add(tbTelExtEntrega);
                this.liTxt.Add(tbFaxExtEntrega);
                this.liTxt.Add(tbFaxEnt);
                //this.liTxt.Add(tEdoEntrega);
                //this.liTxt.Add(tDelMunEnt);
                this.liTxt.Add(tLadaEntrega);
                this.liTxt.Add(tTelEnt);

                //Responsable Fuerza de Ventas
                this.liTxt.Add(tGerencia);
                this.liTxt.Add(tNoClo);

                //Datos Perfil de Ventas
                this.liTxt.Add(tNomDPV);
                this.liTxt.Add(tTelDPV);
                this.liTxt.Add(tTitulo);
                this.liTxt.Add(tMailDPV);
                this.liTxt.Add(tIVA);

                //info Adicional
                this.liTxt.Add(tRespoFV);
                this.liTxt.Add(tNoEmpleado);

                //Datos Bancarios
                this.liTxt.Add(tCuentaBancaria);
                this.liTxt.Add(tSucursal);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public void cargarListCombo()
        {
            try
            {
                //Datos Generales
                this.liCmbx.Add(cTipoSolicitud);
                this.liCmbx.Add(cPersona);

                //Direccion Fiscal
                this.liCmbx.Add(cTipoNegocios);

                //Direccion Entrega
                //this.liCmbx.Add(tCodigoPostal);
                this.liCmbx.Add(cColoniaDistrito);

                //Responsable Fuerza de Ventas
                //this.liCmbx.Add(cCoPoEntrega);
                this.liCmbx.Add(cColDisEntrega);

                //Datos Perfil de Ventas
                this.liCmbx.Add(cTerritorio);
                this.liCmbx.Add(cLeadTime);
                //this.liCmbx.Add(tSubdir);
                this.liCmbx.Add(cCenLog);

                //info Adicional
                this.liCmbx.Add(cZona);
                this.liCmbx.Add(cMedioColoca);
                this.liCmbx.Add(cFrecuencia);

                //Datos Bancarios
                this.liCmbx.Add(cClaveBanco);
                
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
       #endregion

        internal bool ValidarCerradoSolicitud()
        {
            DataTable dt;
            try
            {
                dt = CargarArchivos.GetArchivosSinSolicitud(Convert.ToInt64(sSolicitudDocs));
                if (SolicitudDocs != "-1" && dt.Rows.Count != 0 && dt.Rows[0]["TieneSolicitud"].ToString()=="0")
                {
                    if (MessageBox.Show("Los archivos cargados, no serán guardados, desea continuar?", "¿Desea Salir?", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {
                        borrarDocs(sSolicitudDocs);
                        SaveFiles.solicitudCancelada(sSolicitudDocs);
                        return true;
                    }
                    else
                        return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
               
        }

        private void borrarDocs(string sSolicitudDocs)
        {
            string sDireccion;
            try
            {
                DataTable dtDocs=CargarArchivos.GetArchivosSinSolicitud(Convert.ToInt64(sSolicitudDocs));
                foreach (DataRow rowDoc in dtDocs.Rows)
                {
                    sDireccion = TargetPath + "\\" + rowDoc["GEN_FILE_NAME"].ToString();
                    if (!File.Exists(sDireccion))
                        MessageBox.Show("El archivo no existe", "Archivo No encontrado", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    else
                        File.Delete(sDireccion);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("Error: " + ex.ToString(), "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        internal void llenarUnidsDocumentosPop(long Id_Solicitud)
        {
            DockPanel stackhijo;
            DockPanel stkPanHijoDoc;
            
            DataTable dtDocsExistentes;
            DataRow[] rows;           

            TextBlock txtBlockCnfDoc = new TextBlock();
            TextBlock txtBlockUnidDoc= new TextBlock();
            TextBlock txtBlockPathDoc= new TextBlock();
            TextBlock txtBlockNomGene= new TextBlock();
            TextBlock txtBlockUnidSol = new TextBlock();
            TextBlock txtBlockLinkButton2 = new TextBlock();
            TextBlock txtBlockLinkButton1 = new TextBlock();
            TextBlock tbkhijo;

            Image imgDoc = new Image();
            try
            {
                DataTable dt = CargarArchivos.GetArchivos(Id_Solicitud);
                if (dt.Rows.Count <= 0) return;
                dt.PrimaryKey = new DataColumn[] { dt.Columns["doctos_conf"] };
                dtDocsExistentes = dt.Clone();
                foreach (var childstack in spArchivos.Children)
                    if (childstack.GetType() == typeof(Border))
                    {
                        stackhijo = (DockPanel)((Border)childstack).Child;
                        foreach (var tbkchild in stackhijo.Children)
                            if (tbkchild.GetType() == typeof(System.Windows.Controls.TextBlock) && ((TextBlock)tbkchild).Name == "CnfDoc")
                            {
                                tbkhijo = (TextBlock)tbkchild;
                                rows = dt.Select("doctos_conf = " + tbkhijo.Text);
                                if (rows.Count() != 0)
                                    foreach (DataRow row in rows)
                                        dtDocsExistentes.ImportRow(row);
                                    //dtDocsExistentes.ImportRow(rows);
                                    //dtDocsExistentes = rows.CopyToDataTable();

                            }
                    }

                if (dtDocsExistentes.Rows.Count != 0)
                {
                    foreach (var child1 in spArchivos.Children)
                    {
                        stkPanHijoDoc = (DockPanel)((Border)child1).Child;
                        foreach (var child2 in stkPanHijoDoc.Children)
                        {
                            if (child2.GetType() == typeof(System.Windows.Controls.TextBlock))
                                switch (((TextBlock)child2).Name.ToString())
                                {
                                    case "UnidSol":
                                        txtBlockUnidSol = (TextBlock)child2;
                                        break;

                                    case "UnidDoc":
                                        txtBlockUnidDoc = (TextBlock)child2;
                                        break;

                                    case "CnfDoc":
                                        txtBlockCnfDoc = (TextBlock)child2;
                                        break;

                                    case "nomGene":
                                        txtBlockNomGene = (TextBlock)child2;
                                        break;

                                    case "Path":
                                        txtBlockPathDoc = (TextBlock)child2;
                                        break;

                                    case "Eliminar":
                                        txtBlockLinkButton2 = (TextBlock)child2;
                                        break;

                                    case "AdjAbr":
                                        txtBlockLinkButton1 = (TextBlock)child2;
                                        break;

                                }
                            if (child2.GetType() == typeof(Image))
                                imgDoc = (Image)child2;
                        }
                        rows = dtDocsExistentes.Select("doctos_conf = " + txtBlockCnfDoc.Text);
                        if (rows.Count() != 0)
                        {
                            txtBlockUnidDoc.Text = rows[0]["doctos_unidDoc"].ToString();
                            txtBlockNomGene.Text = rows[0]["doctos_genFile"].ToString();
                            txtBlockPathDoc.Text = targetPath +"\\"+ rows[0]["doctos_genFile"].ToString();
                            txtBlockUnidSol.Text = Id_Solicitud.ToString();

                            BitmapImage bi1 = new BitmapImage();
                            bi1.CacheOption = BitmapCacheOption.OnLoad;
                            bi1.BeginInit();
                            bi1.UriSource = new Uri("Images/icon_validar_001.png", UriKind.Relative);
                            bi1.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                            bi1.EndInit();
                            imgDoc.Stretch = Stretch.Fill;
                            imgDoc.Name = "imagen";
                            imgDoc.Source = bi1;
                            imgDoc.Margin = new Thickness(9);
                            imgDoc.Height = 10;
                            imgDoc.Width = 10;
                            imgDoc.HorizontalAlignment = HorizontalAlignment.Left;
                            txtBlockLinkButton1.Text = "Abrir";
                            txtBlockLinkButton2.IsEnabled = (lbl_idStatus.Content.ToString() == "-1" || lbl_idStatus.Content.ToString() == "1" || lbl_idStatus.Content.ToString() == "6") ? true : false;
                            txtBlockLinkButton2.Foreground = (lbl_idStatus.Content.ToString() == "-1" || lbl_idStatus.Content.ToString() == "1" || lbl_idStatus.Content.ToString() == "6") ? Brushes.Blue : Brushes.Silver;

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error al cargar detalles de documentos:" + ex.ToString(), "ERROR",MessageBoxButton.OK,MessageBoxImage.Error);
            }

        }
        
        private void DocCarga(DataTable dataTable)
        {
            int indice = 0;

            StackPanel stkPanHijo;

            TextBlock txtBlockTipoDocLetra;
            TextBlock txtBlockCnfDoc;
            TextBlock txtBlockRuleDoc;
            TextBlock txtBlockUnidSol;
            TextBlock txtBlockUnidDoc;
            TextBlock txtBlockPathDoc;
            TextBlock txtBlockNomGene;

            Label lbl_Ext;
            //Image imagen;
            try
            {

                foreach (var stackHijo in spArchivos.Children)
                {
                    stkPanHijo = (StackPanel)stackHijo;
                    foreach (var objNieto in stkPanHijo.Children)
                    {

                        if (objNieto.GetType() == typeof(System.Windows.Controls.TextBlock))
                            switch (((TextBlock)objNieto).Name.ToString())
                            {
                                case "UnidSol":
                                    txtBlockUnidSol = (TextBlock)objNieto;
                                    break;

                                case "UnidDoc":
                                    txtBlockUnidDoc = (TextBlock)objNieto;
                                    break;

                                case "unidRuleDoc":
                                    txtBlockRuleDoc = (TextBlock)objNieto;
                                    break;

                                case "CnfDoc":
                                    txtBlockCnfDoc = (TextBlock)objNieto;
                                    break;

                                case "nomGene":
                                    txtBlockNomGene = (TextBlock)objNieto;
                                    break;

                                case "Path":
                                    txtBlockPathDoc = (TextBlock)objNieto;
                                    break;

                                case "Documento":
                                    txtBlockTipoDocLetra = (TextBlock)objNieto;
                                    break;
                            }
                        lbl_Ext = new Label();
                        txtBlockTipoDocLetra = new TextBlock();
                        txtBlockCnfDoc = new TextBlock();
                        txtBlockRuleDoc = new TextBlock();
                        txtBlockUnidSol = new TextBlock();
                        txtBlockPathDoc = new TextBlock();
                        txtBlockUnidDoc = new TextBlock();
                        txtBlockNomGene = new TextBlock();

                        txtBlockUnidSol.Name = "UnidSol";
                        txtBlockUnidSol.Visibility = Visibility.Hidden;
                        txtBlockUnidSol.Text = "-1";

                        txtBlockPathDoc.Name = "Path";
                        txtBlockPathDoc.Visibility = Visibility.Hidden;
                        txtBlockPathDoc.Text = "";
                        lbl_Ext.Content = dataTable.Rows[indice]["TYPE_DOC"].ToString();
                        txtBlockPathDoc.Tag = lbl_Ext;
                        txtBlockPathDoc.Visibility = Visibility.Hidden;

                        txtBlockUnidDoc.Name = "UnidDoc";
                        txtBlockUnidDoc.Text = "-1";
                        txtBlockUnidDoc.Visibility = Visibility.Hidden;

                        txtBlockTipoDocLetra.Name = "Documento";
                        txtBlockTipoDocLetra.Text = dataTable.Rows[indice]["DOCUMENTO"].ToString();

                        txtBlockCnfDoc.Name = "CnfDoc";
                        txtBlockCnfDoc.Text = dataTable.Rows[indice]["UNID_CNF_DOCUMENTO"].ToString();
                        txtBlockCnfDoc.Visibility = Visibility.Hidden;

                        txtBlockRuleDoc.Name = "unidRuleDoc";
                        txtBlockRuleDoc.Text = dataTable.Rows[indice]["UNID_CNF_RULEDOC"].ToString();
                        txtBlockRuleDoc.Visibility = Visibility.Hidden;

                        txtBlockNomGene.Name = "nomGene";
                        txtBlockNomGene.Visibility = Visibility.Hidden;
                        txtBlockNomGene.Text = "";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error al cargar Documentos:" + ex.ToString(), "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        #region Propiedades

        public int CheckMismoDomicilio
        {
            get 
            { return (System.Convert.ToBoolean(chMismoDom.IsChecked)) ? 1 : 0; }
            
        }

        public StackPanel StackDocs
        {
            get { return spArchivos; }
            set { spArchivos = value; }

        }

        public int Check
        {
            set { check = value; }

        }
        public string Ctiposol
        {
            set { ctiposol = value; }

        }
        public string Cperso
        {
            set { cperso = value; }

        }
        public string TargetPath
        {
            set { targetPath = value; }
            get { return targetPath; }
        }

        public string SolicitudDocs
        {
            set { sSolicitudDocs = value; }
            get { return sSolicitudDocs; }
        }
        #endregion


        public virtual Solicitud GetDatatoSave(object sender)
        {
            if (sol.Unid_solicitud != 0)
                lbl_unidSol.Content = sol.Unid_solicitud.ToString();
            if (sol.Unid_docinfo != 0)
                lbl_unidDocinfo.Content = sol.Unid_docinfo.ToString();
            if (sol.Unid_datos != 0)
                lbl_unidDatos.Content = sol.Unid_datos.ToString();
            if (sol.Unid_datosgral != 0)
                lbl_unidDatgral.Content = sol.Unid_datosgral.ToString();
            if (sol.Unid_dirfiscal != 0)
                lbl_unidDirFiscal.Content = sol.Unid_dirfiscal.ToString();
            if (sol.Unid_direntrega != 0)
                lbl_unidDirEntrega.Content = sol.Unid_direntrega.ToString();
            if (sol.Unid_rfv != 0)
                lbl_unidRFV.Content = sol.Unid_rfv.ToString();
            if (sol.Unid_dpv != 0)
                lbl_unidDPV.Content = sol.Unid_dpv.ToString();
            if (sol.Unid_infoad != 0)
                lbl_unidInfoad.Content = sol.Unid_infoad.ToString();
            if (sol.Unid_datosbanc != 0)
                lbl_unidBanc.Content = sol.Unid_datosbanc.ToString();
            if (sol.Unid_documentos != 0)
                lbl_unidDocumentos.Content = sol.Unid_documentos.ToString();
            if (sol.Id_status != 0)
                lbl_idStatus.Content = sol.Id_status.ToString();
            if (sol.Id_prioridad != 0)
                lbl_idPrioridad.Content = sol.Id_prioridad.ToString();
            if (sol.Id_tipo != 0)
                lbl_idTipo.Content = sol.Id_tipo.ToString();

            sol.parametros.Clear();

            #region parametros
            //Solicitud sol = new Solicitud();
            // ----------   DOCINFO
            sol.SetDictionaryParameterValues("docInfo_unidDocInfo", lbl_unidDocinfo.Content.ToString());
            // ----------   STATUS, PRIORIDAD Y TIPO
            sol.SetDictionaryParameterValues("sol_idTipoSol", lbl_idTipo.Content.ToString()); //alta
            sol.SetDictionaryParameterValues("sol_idPrio", lbl_idPrioridad.Content.ToString());
            sol.SetDictionaryParameterValues("sol_idSolStat", lbl_idStatus.Content.ToString()); //borrador
            if(sender.GetType()==typeof(System.Windows.Controls.Image))
                if (((Image)sender).Name =="img_Enviar")
                    sol.SetDictionaryParameterValues("sol_unid_rol", AppConfs.Unid_datosMaestros.ToString());
            //----------- DOCUMENTOS
            if (SolicitudDocs.Trim() != "-1" && SolicitudDocs.Trim() != "0")
                sol.SetDictionaryParameterValues("doctos_unidDoctos", SolicitudDocs);

            foreach (var child in spAlta.Children)
            {
                if (child.GetType() == typeof(System.Windows.Controls.Grid))
                {
                    Grid chldGrid = (Grid)child;
                    switch (chldGrid.Name)
                    {
                        case "mainGrid":
                            sol.SetDictionaryParameterValues("unidSolicitud", lbl_unidSol.Content.ToString());
                            sol.SetDictionaryParameterValues("datsol_unidSolicitudDatos", lbl_unidDatos.Content.ToString());

                            sol.SetDictionaryParameterValues("datsol_unidTipoSolicitante", cTipoSolicitud.SelectedValue.ToString());
                            sol.SetDictionaryParameterValues("datsol_isMismoDomicilio", Convert.ToInt32(chMismoDom.IsChecked).ToString());
                            sol.SetDictionaryParameterValues("datsol_isProveedor", Convert.ToInt32(chProveedor.IsChecked).ToString());
                            sol.SetDictionaryParameterValues("datsol_isOtrasCategorias", Convert.ToInt32(chOtrasCateg.IsChecked).ToString());
                            sol.SetDictionaryParameterValues("datsol_isOtrosClientes", Convert.ToInt32(chOtrosClientes.IsChecked).ToString());
                            sol.SetDictionaryParameterValues("datsol_idTipoPersonaFiscal", cPersona.SelectedValue.ToString());

                            break;
                        case "gdDatosGenerales":
                            sol.SetDictionaryParameterValues("datgral_unidSolicitud", lbl_unidDatgral.Content.ToString());
                            sol.SetDictionaryParameterValues("datgral_idTipoNeg", cTipoNegocios.SelectedValue.ToString());
                            sol.SetDictionaryParameterValues("datgral_razonSocial", tRazonSocial.Text);
                            sol.SetDictionaryParameterValues("datgral_rfc", tRFC.Text);
                            sol.SetDictionaryParameterValues("datgral_correo", tEmail.Text);
                            sol.SetDictionaryParameterValues("datgral_nombreSucursal", tNombreSucursal.Text);
                            sol.SetDictionaryParameterValues("datgral_numSucursal", tNumeroSucursal.Text);
                            sol.SetDictionaryParameterValues("datgral_idGrupoClientes4", cGrupoClientes4.SelectedValue.ToString());

                            break;
                        case "gdDatosFiscales":
                            sol.SetDictionaryParameterValues("dirFis_unidDirFiscal", lbl_unidDirFiscal.Content.ToString());
                            sol.SetDictionaryParameterValues("dirFis_calle", tCalle.Text);
                            sol.SetDictionaryParameterValues("dirFis_numExt", tNoExterior.Text);
                            sol.SetDictionaryParameterValues("dirFis_numInt", tNoInterior.Text);
                            sol.SetDictionaryParameterValues("dirFis_unidSepomex",  UnidDirFiscal);//tCodigoPostal.Text.ToString());
                            sol.SetDictionaryParameterValues("dirFis_lada", tLada.Text);
                            sol.SetDictionaryParameterValues("dirFis_tel", tTelFiscal.Text);
                            sol.SetDictionaryParameterValues("dirFis_local", (cLocalidad.DataContext != null) ? cLocalidad.SelectedValue.ToString() : "");
                            sol.SetDictionaryParameterValues("dirFis_TelExtFiscal", tbTelExtFiscal.Text);
                            sol.SetDictionaryParameterValues("dirFis_FaxFiscal", tbFaxFiscal.Text);
                            sol.SetDictionaryParameterValues("dirFis_FaxExtFiscal", tbFaxExtFiscal.Text);

                            break;
                        case "gdDirEntrega":
                            sol.SetDictionaryParameterValues("dirEnt_unidDirEntrega", lbl_unidDirEntrega.Content.ToString());
                            sol.SetDictionaryParameterValues("dirEnt_calle", tCalleEntrega.Text);
                            sol.SetDictionaryParameterValues("dirEnt_numExt", tNoExtEntrega.Text);
                            sol.SetDictionaryParameterValues("dirEnt_numInt", tNoInEntrega.Text);
                            //sol.SetDictionaryParameterValues("dirEnt_unidSepomex", cCoPoEntrega.SelectedValue.ToString());
                            sol.SetDictionaryParameterValues("dirEnt_unidSepomex",  UnidDirEntrega);//tCoPoEntrega.Text.ToString());
                            sol.SetDictionaryParameterValues("dirEnt_lada", tLadaEntrega.Text);
                            sol.SetDictionaryParameterValues("dirEnt_tel", tTelEnt.Text);
                            sol.SetDictionaryParameterValues("dirEnt_local", (cLocalidadEnt.DataContext != null) ? cLocalidadEnt.SelectedValue.ToString() : "");
                            sol.SetDictionaryParameterValues("dirEnt_TelExtEntrega", tbTelExtEntrega.Text);
                            sol.SetDictionaryParameterValues("dirEnt_FaxEnt", tbFaxEnt.Text);
                            sol.SetDictionaryParameterValues("dirEnt_FaxExtEntrega", tbFaxExtEntrega.Text);

                            break;
                        case "gdRFV":
                            sol.SetDictionaryParameterValues("datRFV_unidRFV", lbl_unidRFV.Content.ToString());
                            sol.SetDictionaryParameterValues("datRFV_ter", cTerritorio.SelectedValue.ToString());
                            sol.SetDictionaryParameterValues("datRFV_idLeadTime", cLeadTime.SelectedValue.ToString());
                            sol.SetDictionaryParameterValues("datRFV_subdir", tSubdir.Text.ToString());
                            sol.SetDictionaryParameterValues("datRFV_geren", tGerencia.Text);
                            sol.SetDictionaryParameterValues("datRFV_idClo", cCenLog.SelectedValue.ToString());

                            break;
                        case "gdDatosPV":
                            string diasCol = "";
                            string diasEnt = "";
                            foreach (var item in chldGrid.Children)
                            {
                                if (item.GetType() == typeof(System.Windows.Controls.CheckBox))
                                {
                                    CheckBox chbx = (CheckBox)item;
                                    if (chbx.Name.Contains("chbDiaC"))
                                    {
                                        if (chbx.IsChecked.Value)
                                        {
                                            if (diasCol == "") diasCol = "1";
                                            else diasCol = diasCol + ",1";
                                        }
                                        else
                                        {
                                            if (diasCol == "") diasCol = "0";
                                            else diasCol = diasCol + ",0";
                                        }
                                    }
                                    else if (chbx.Name.Contains("chbDiaE"))
                                    {
                                        if (chbx.IsChecked.Value)
                                        {
                                            if (diasEnt == "") diasEnt = "1";
                                            else diasEnt = diasEnt + ",1";
                                        }
                                        else
                                        {
                                            if (diasEnt == "") diasEnt = "0";
                                            else diasEnt = diasEnt + ",0";
                                        }
                                    }//if-else
                                }//if
                            }//foreach

                            sol.SetDictionaryParameterValues("datDPV_unidDPV", lbl_unidDPV.Content.ToString());
                            sol.SetDictionaryParameterValues("datDPV_nom", tNomDPV.Text);
                            sol.SetDictionaryParameterValues("datDPV_tel", tTelDPV.Text);
                            sol.SetDictionaryParameterValues("datDPV_titulo", tTitulo.Text);
                            sol.SetDictionaryParameterValues("datDPV_correo", tMailDPV.Text);
                            sol.SetDictionaryParameterValues("datDPV_idZona", cZona.SelectedValue.ToString());
                            sol.SetDictionaryParameterValues("datDPV_diasCol", diasCol);
                            sol.SetDictionaryParameterValues("datDPV_diasEnt", diasEnt);
                            sol.SetDictionaryParameterValues("datDPV_idMedCol", cMedioColoca.SelectedValue.ToString());
                            sol.SetDictionaryParameterValues("datDPV_idFrec", cFrecuencia.SelectedValue.ToString());
                            sol.SetDictionaryParameterValues("datDPV_grupoPrecio", lbl_GrupoPrecios.Content.ToString());
                            sol.SetDictionaryParameterValues("datDPV_idIva", tIVA.Text);
                            //TODO: bind medios de colocación, frecuencia, gpo de precios

                            break;
                        case "gdInfoAd":
                            sol.SetDictionaryParameterValues("infoad_unidInfoad", lbl_unidInfoad.Content.ToString());
                            sol.SetDictionaryParameterValues("infoad_respoFDV", tRespoFV.Text);
                            sol.SetDictionaryParameterValues("infoad_numEmpleado", tNoEmpleado.Text);

                            break;
                        case "gdDatosBanc":
                            sol.SetDictionaryParameterValues("datBnc_unidBanc", lbl_unidBanc.Content.ToString());
                            sol.SetDictionaryParameterValues("datBnc_idBanc", cClaveBanco.SelectedValue.ToString());
                            sol.SetDictionaryParameterValues("datBnc_ctaBanc", tCuentaBancaria.Text);
                            sol.SetDictionaryParameterValues("datBnc_suc", tSucursal.Text);

                            break;
                        default:
                            break;
                    }//end switch
                }//if
            }//foreach

            #endregion
            //pop.HidePopup();
            return sol;
        }

        virtual public void lblEnviar_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            pop = new CMDPopUp();

            //pop.showPopup("Validando y guardando\nEspere por favor...", PanelAccion);
            lbl_Saving.Content = "Validando y guardando, espere un momento...";
        }


        private void getSepomex()
        {

            DataTable dt;
            bool bandera = true;
            try
            {
                if (!ValidarGuardado())
                    return;

                if (ValidarCodigoPostal(tCodigoPostal) && cColoniaDistrito.DataContext != null)
                {
                    dt = Sepomex.GetCodigoPostalUnid(tCodigoPostal.Text, (cColoniaDistrito.SelectedValue == null) ? "" : cColoniaDistrito.SelectedValue.ToString());
                    if (dt.Rows.Count == 0)
                        UnidDirFiscal = "";
                    else
                        UnidDirFiscal = dt.Rows[0]["UNID_SEPOMEX"].ToString();

                    if (chMismoDom.IsChecked == true) UnidDirEntrega = UnidDirFiscal;
                    else
                    {
                        dt = Sepomex.GetCodigoPostalUnid(tCoPoEntrega.Text, (cColDisEntrega.SelectedValue == null) ? "" : cColDisEntrega.SelectedValue.ToString());
                        if (dt.Rows.Count == 0)
                            UnidDirEntrega = "";
                        else
                            UnidDirEntrega = dt.Rows[0]["UNID_SEPOMEX"].ToString();
                    }
                }
                else
                {
                    UnidDirEntrega = "";
                    UnidDirFiscal = "";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("error: llenar uid dir entrega " + ex.ToString(), "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public void lblEnviar_MouseUp(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Media.Animation.Storyboard sb = (System.Windows.Media.Animation.Storyboard)Application.Current.Windows[0].FindResource("rotateImg");
            MainWindow mw = (MainWindow)App.Current.MainWindow;
            
            
            if (!spAlta.IsEnabled)
            {
                //pop.HidePopup();
                lbl_Saving.Content = "";
                MessageBox.Show("La solicitud se encuentra en un estatus distinto de Borrador, no es posible modificarla.",
                    "Mensaje del Sistema", MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK, MessageBoxOptions.DefaultDesktopOnly);
                
                return;
            }
            // CAMBIAR EL STATUS DE LA SOLICITUD, DE BORRADOR A ENVIANDO
            long unid;
            try
            {
                // ------------------- VALIDACION DE CAMPOS
                if (!ValidarEnviado())
                {
                    //pop.HidePopup();
                    lbl_Saving.Content = "";
                    return;
                }

                if (MessageBox.Show("¿Está seguro de enviar la solicitud en este momento?", "Mensaje del Sistema", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.OK, MessageBoxOptions.DefaultDesktopOnly)
                == MessageBoxResult.No)
                {
                    //pop.HidePopup();
                    lbl_Saving.Content = "";
                    return;
                }
                lbl_Saving.Content = "Validando y guardando, espere un momento...";
                Mouse.OverrideCursor = Cursors.Wait;
                // ------------------- GUARDADO DE SOLICITUD ACTUAL
                getSepomex();
                sol = GetDatatoSave(sender);



                ThreadUI.sol = this.sol;
                ThreadUI.save(true);

                if (lbl_unidSol.Content.ToString() != "-1" && lbl_unidSol.Content.ToString() != "0")
                    sol.Unid_solicitud = long.Parse(lbl_unidSol.Content.ToString());

                if (sol.Unid_solicitud > 0)
                {
                    // ---------------- CAMBIO DE STATUS DE LA SOLICITUD ACTUAL
                    unid = long.Parse(sol.Unid_solicitud.ToString());

                    if (!sol.InsertNewRol(unid))
                        MessageBox.Show("Ha ocurrido un error en el envio de la solicitud", "Mensaje del sistema", MessageBoxButton.OK, MessageBoxImage.Error);

                    if (sol.UpdateSolStatus(unid, AppConfs.Status_Enviado, AppConfs.Unid_datosMaestros))
                        MessageBox.Show("Se ha enviado su solicitud.", "Mensaje del sistema", MessageBoxButton.OK, MessageBoxImage.Information);

                    //pop.HidePopup();
                    mw.BloqueoMenus(false);
                    //----------------- ENVIADO DE SOLICITUDES
                    new System.Threading.Thread(delegate()
                    {
                        Sync.start(sb, mw);
                    }).Start();

                    if (mw.Despliega1 != null)
                        mw.Despliega1.RefreshContadores();

                    // ------------------ RETORNO AL GRID
                    PanelCentral.Content = null;//SaveFiles.solicitudCancelada(sSolicitudDocs); 
                    lbl_Saving.Content = "";
                    //Sol.UISolicitudes Despliega = new Sol.UISolicitudes(PanelAccion, PanelNavegacion, PanelCentral);
                    if(mw.Despliega1 != null)
                        mw.Despliega1 = new Sol.UISolicitudes(PanelAccion, PanelNavegacion, PanelCentral);
                    return;
                }
                else
                {
                    MessageBox.Show("Debe guardar la solicitud, antes de enviar la solicitud.", "Mensaje del sistema", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    //pop.HidePopup();
                    lbl_Saving.Content = "";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Mouse.OverrideCursor = null;
                lbl_Saving.Content = "";
                mw.BloqueoMenus(true);
            }

        }


        void  tbFaxExtFiscal_TextChanged(object sender, TextChangedEventArgs e)
        {
 	        if (chMismoDom.IsChecked == true)
                tbFaxExtEntrega.Text = tbFaxExtFiscal.Text;
        }

        void  tbFaxFiscal_TextChanged(object sender, TextChangedEventArgs e)
        {
 	        if (chMismoDom.IsChecked == true)
                tbFaxEnt.Text = tbFaxFiscal.Text ;
        }

        void  tbTelExtFiscal_TextChanged(object sender, TextChangedEventArgs e)
        {
 	        if (chMismoDom.IsChecked == true)
                tbTelExtEntrega.Text = tbTelExtFiscal.Text;
        }

        private bool ValidarDiasColoc()
        {
            RowDefinition row = new RowDefinition();
            if (chDiaCL.IsChecked == true ||
                chDiaCM.IsChecked == true ||
                chDiaCMi.IsChecked == true ||
                chDiaCJ.IsChecked == true ||
                chDiaCV.IsChecked == true ||
                chDiaCS.IsChecked == true)
            {
                brdr_diasCol.Background = new SolidColorBrush(Colors.White);
                chDiaCL.Foreground = new SolidColorBrush(Colors.Black);
                chDiaCM.Foreground = new SolidColorBrush(Colors.Black);
                chDiaCMi.Foreground = new SolidColorBrush(Colors.Black);
                chDiaCJ.Foreground = new SolidColorBrush(Colors.Black);
                chDiaCV.Foreground = new SolidColorBrush(Colors.Black);
                chDiaCS.Foreground = new SolidColorBrush(Colors.Black);
                return true;
            }
            else
            {
                try
                {
                    brdr_diasCol.Background = new SolidColorBrush(Colors.Red);
                    chDiaCL.Foreground = new SolidColorBrush(Colors.White);
                    chDiaCM.Foreground = new SolidColorBrush(Colors.White);
                    chDiaCMi.Foreground = new SolidColorBrush(Colors.White);
                    chDiaCJ.Foreground = new SolidColorBrush(Colors.White);
                    chDiaCV.Foreground = new SolidColorBrush(Colors.White);
                    chDiaCS.Foreground = new SolidColorBrush(Colors.White);
                    return false;
                }
                catch
                {
                    return false;
                }
            }
        }
        public void pintarError(object sender)
        {
            ((TextBox)sender).BorderBrush = new SolidColorBrush(Colors.Red);
            ((TextBox)sender).Background = new SolidColorBrush(Colors.Red);
            ((TextBox)sender).Foreground = new SolidColorBrush(Colors.White);
        }
        public void pintarCorrecto(object sender)
        {
            ((TextBox)sender).BorderBrush = new SolidColorBrush(SystemColors.ActiveBorderColor);
            ((TextBox)sender).Background = new SolidColorBrush(Colors.White);
            ((TextBox)sender).Foreground = new SolidColorBrush(Colors.Black);
        }

        public void BloqueoMenus(bool activar)
        {
            if (!activar)
            {
                lblEnviar.Opacity = 0.5;
                lblEnviar.Cursor = Cursors.Arrow;
                lblGuardar.Opacity = 0.5;
                lblGuardarYSalir.Opacity = 0.5;
            }
            else
            {
                lblGuardarYSalir.Opacity = 1.0;
                lblGuardar.Opacity = 1.0;
                lblEnviar.Opacity = 1.0;
                lblEnviar.Cursor = Cursors.Hand;
            }
            lblEnviar.IsEnabled = activar;
            lblGuardar.IsEnabled = activar;
            lblGuardarYSalir.IsEnabled = activar;
        }
    }  
}